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
32 #include <sys/socket.h>
33 #include <netinet/in.h>
41 #include <sys/types.h>
42 #include <arpa/inet.h>
46 #include <openssl/ssl.h>
47 #include <openssl/rand.h>
48 #include <openssl/err.h>
49 #include <openssl/md5.h>
50 #include <openssl/hmac.h>
51 #include <openssl/x509v3.h>
56 #include "radsecproxy.h"
58 static struct options options;
59 struct list *clconfs, *srvconfs, *realms, *tlsconfs, *rewriteconfs;
61 static int client_udp_count = 0;
62 static int client_tls_count = 0;
63 static int server_udp_count = 0;
64 static int server_tls_count = 0;
66 static struct clsrvconf *srcudpres = NULL;
67 static struct clsrvconf *srctcpres = NULL;
69 static struct replyq *udp_server_replyq = NULL;
70 static int udp_server_sock = -1;
71 static int udp_accserver_sock = -1;
72 static int udp_client4_sock = -1;
73 static int udp_client6_sock = -1;
74 static pthread_mutex_t *ssl_locks;
75 static long *ssl_lock_count;
79 /* callbacks for making OpenSSL thread safe */
80 unsigned long ssl_thread_id() {
81 return (unsigned long)pthread_self();
84 void ssl_locking_callback(int mode, int type, const char *file, int line) {
85 if (mode & CRYPTO_LOCK) {
86 pthread_mutex_lock(&ssl_locks[type]);
87 ssl_lock_count[type]++;
89 pthread_mutex_unlock(&ssl_locks[type]);
92 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
93 int pwdlen = strlen(userdata);
94 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
96 memcpy(buf, userdata, pwdlen);
100 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
105 err_cert = X509_STORE_CTX_get_current_cert(ctx);
106 err = X509_STORE_CTX_get_error(ctx);
107 depth = X509_STORE_CTX_get_error_depth(ctx);
109 if (depth > MAX_CERT_DEPTH) {
111 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
112 X509_STORE_CTX_set_error(ctx, err);
116 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
117 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
120 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
121 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
122 debug(DBG_WARN, "\tIssuer=%s", buf);
124 case X509_V_ERR_CERT_NOT_YET_VALID:
125 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
126 debug(DBG_WARN, "\tCertificate not yet valid");
128 case X509_V_ERR_CERT_HAS_EXPIRED:
129 debug(DBG_WARN, "Certificate has expired");
131 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
132 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
137 printf("certificate verify returns %d\n", ok);
142 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
143 struct addrinfo hints, *addrinfo, *res;
147 slash = conf->host ? strchr(conf->host, '/') : NULL;
151 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
155 if (*s < '0' || *s > '9') {
156 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
159 plen = atoi(slash + 1);
160 if (plen < 0 || plen > 128) {
161 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
166 memset(&hints, 0, sizeof(hints));
167 hints.ai_socktype = (conf->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
168 hints.ai_family = AF_UNSPEC;
169 hints.ai_flags = ai_flags;
170 if (!conf->host && !conf->port) {
171 /* getaddrinfo() doesn't like host and port to be NULL */
172 if (getaddrinfo(conf->host, DEFAULT_UDP_PORT, &hints, &addrinfo)) {
173 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
176 for (res = addrinfo; res; res = res->ai_next) {
177 switch (res->ai_family) {
179 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
182 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
188 hints.ai_flags |= AI_NUMERICHOST;
189 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
190 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
195 switch (addrinfo->ai_family) {
198 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
199 freeaddrinfo(addrinfo);
206 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
207 freeaddrinfo(addrinfo);
210 conf->prefixlen = plen;
212 conf->prefixlen = 255;
215 freeaddrinfo(conf->addrinfo);
216 conf->addrinfo = addrinfo;
220 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
222 struct addrinfo *res;
224 for (res = addrinfo; res; res = res->ai_next) {
225 if (family != AF_UNSPEC && family != res->ai_family)
227 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
229 debug(DBG_WARN, "bindtoaddr: socket failed");
233 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
236 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
239 if (!bind(s, res->ai_addr, res->ai_addrlen))
241 debug(DBG_WARN, "bindtoaddr: bind failed");
247 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
252 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
256 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
258 debugx(1, DBG_ERR, "no ] matching initial [");
262 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
265 debugx(1, DBG_ERR, "missing host/address");
267 conf->host = stringcopy(field, p - field);
270 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
271 debugx(1, DBG_ERR, "unexpected character after ]");
274 /* port number or service name is specified */;
276 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
278 debugx(1, DBG_ERR, "syntax error, : but no following port");
279 conf->port = stringcopy(field, p - field);
281 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
285 struct clsrvconf *resolve_hostport(char type, char *lconf, char *default_port) {
286 struct clsrvconf *conf;
288 conf = malloc(sizeof(struct clsrvconf));
290 debugx(1, DBG_ERR, "malloc failed");
291 memset(conf, 0, sizeof(struct clsrvconf));
294 parsehostport(lconf, conf, default_port);
295 if (!strcmp(conf->host, "*")) {
300 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
301 if (!resolvepeer(conf, AI_PASSIVE))
302 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
306 int connecttcp(struct addrinfo *addrinfo) {
308 struct addrinfo *res;
311 for (res = addrinfo; res; res = res->ai_next) {
312 s = bindtoaddr(srctcpres->addrinfo, res->ai_family, 1, 1);
314 debug(DBG_WARN, "connecttoserver: socket failed");
317 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
319 debug(DBG_WARN, "connecttoserver: connect failed");
326 /* returns 1 if the len first bits are equal, else 0 */
327 int prefixmatch(void *a1, void *a2, uint8_t len) {
328 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
330 if (l && memcmp(a1, a2, l))
335 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
338 /* returns the config with matching address, or NULL */
339 /* if conf argument is not NULL, we only check that one */
340 struct clsrvconf *find_conf(char type, struct sockaddr *addr, struct list *confs, struct clsrvconf *conf) {
341 struct sockaddr_in6 *sa6 = NULL;
342 struct in_addr *a4 = NULL;
343 struct addrinfo *res;
344 struct list_node *entry;
346 if (addr->sa_family == AF_INET6) {
347 sa6 = (struct sockaddr_in6 *)addr;
348 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
349 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
353 a4 = &((struct sockaddr_in *)addr)->sin_addr;
356 if (conf->type == type) {
357 if (conf->prefixlen == 255) {
358 for (res = conf->addrinfo; res; res = res->ai_next)
359 if ((a4 && res->ai_family == AF_INET &&
360 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
361 (sa6 && res->ai_family == AF_INET6 &&
362 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
365 res = conf->addrinfo;
367 ((a4 && res->ai_family == AF_INET &&
368 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
369 (sa6 && res->ai_family == AF_INET6 &&
370 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
377 for (entry = list_first(confs); entry; entry = list_next(entry)) {
378 conf = (struct clsrvconf *)entry->data;
379 if (conf->type == type) {
380 if (conf->prefixlen == 255) {
381 for (res = conf->addrinfo; res; res = res->ai_next)
382 if ((a4 && res->ai_family == AF_INET &&
383 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
384 (sa6 && res->ai_family == AF_INET6 &&
385 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
388 res = conf->addrinfo;
390 ((a4 && res->ai_family == AF_INET &&
391 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
392 (sa6 && res->ai_family == AF_INET6 &&
393 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
401 struct replyq *newreplyq() {
402 struct replyq *replyq;
404 replyq = malloc(sizeof(struct replyq));
406 debugx(1, DBG_ERR, "malloc failed");
407 replyq->replies = list_create();
408 if (!replyq->replies)
409 debugx(1, DBG_ERR, "malloc failed");
410 pthread_mutex_init(&replyq->mutex, NULL);
411 pthread_cond_init(&replyq->cond, NULL);
415 struct client *addclient(struct clsrvconf *conf) {
416 struct client *new = malloc(sizeof(struct client));
419 debug(DBG_ERR, "malloc failed");
422 if (!conf->clients) {
423 conf->clients = list_create();
424 if (!conf->clients) {
425 debug(DBG_ERR, "malloc failed");
430 memset(new, 0, sizeof(struct client));
432 new->replyq = conf->type == 'T' ? newreplyq() : udp_server_replyq;
434 list_push(conf->clients, new);
438 void removeclient(struct client *client) {
439 struct list_node *entry;
441 if (!client || !client->conf->clients)
444 pthread_mutex_lock(&client->replyq->mutex);
445 for (entry = list_first(client->replyq->replies); entry; entry = list_next(entry))
446 free(((struct reply *)entry)->buf);
447 list_destroy(client->replyq->replies);
448 pthread_mutex_unlock(&client->replyq->mutex);
449 list_removedata(client->conf->clients, client);
453 void removeclientrqs(struct client *client) {
454 struct list_node *entry;
455 struct server *server;
459 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
460 server = ((struct clsrvconf *)entry->data)->servers;
461 pthread_mutex_lock(&server->newrq_mutex);
462 for (i = 0; i < MAX_REQUESTS; i++) {
463 rq = server->requests + i;
464 if (rq->from == client)
467 pthread_mutex_unlock(&server->newrq_mutex);
471 void addserver(struct clsrvconf *conf) {
473 debugx(1, DBG_ERR, "addserver: currently works with just one server per conf");
475 conf->servers = malloc(sizeof(struct server));
477 debugx(1, DBG_ERR, "malloc failed");
478 memset(conf->servers, 0, sizeof(struct server));
479 conf->servers->conf = conf;
481 if (conf->type == 'U') {
483 srcudpres = resolve_hostport('U', options.sourceudp, NULL);
484 switch (conf->addrinfo->ai_family) {
486 if (udp_client4_sock < 0) {
487 udp_client4_sock = bindtoaddr(srcudpres->addrinfo, AF_INET, 0, 1);
488 if (udp_client4_sock < 0)
489 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
491 conf->servers->sock = udp_client4_sock;
494 if (udp_client6_sock < 0) {
495 udp_client6_sock = bindtoaddr(srcudpres->addrinfo, AF_INET6, 0, 1);
496 if (udp_client6_sock < 0)
497 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
499 conf->servers->sock = udp_client6_sock;
502 debugx(1, DBG_ERR, "addserver: unsupported address family");
507 srctcpres = resolve_hostport('T', options.sourcetcp, NULL);
508 conf->servers->sock = -1;
511 pthread_mutex_init(&conf->servers->lock, NULL);
512 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
513 if (!conf->servers->requests)
514 debugx(1, DBG_ERR, "malloc failed");
515 conf->servers->newrq = 0;
516 pthread_mutex_init(&conf->servers->newrq_mutex, NULL);
517 pthread_cond_init(&conf->servers->newrq_cond, NULL);
520 /* exactly one of client and server must be non-NULL */
521 /* should probably take peer list (client(s) or server(s)) as argument instead */
522 /* if *peer == NULL we return who we received from, else require it to be from peer */
523 /* return from in sa if not NULL */
524 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
526 unsigned char buf[65536], *rad;
527 struct sockaddr_storage from;
528 socklen_t fromlen = sizeof(from);
530 struct list_node *node;
533 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
535 debug(DBG_WARN, "radudpget: recv failed");
538 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
541 debug(DBG_WARN, "radudpget: packet too small");
547 debug(DBG_WARN, "radudpget: length too small");
552 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
556 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
560 p = find_conf('U', (struct sockaddr *)&from, NULL, (*client)->conf);
562 p = find_conf('U', (struct sockaddr *)&from, clconfs, NULL);
565 p = find_conf('U', (struct sockaddr *)&from, NULL, (*server)->conf);
567 p = find_conf('U', (struct sockaddr *)&from, srvconfs, NULL);
570 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer, ignoring");
576 debug(DBG_ERR, "radudpget: malloc failed");
580 if (client && !*client) {
581 node = list_first(p->clients);
582 *client = node ? (struct client *)node->data : addclient(p);
587 } else if (server && !*server)
588 *server = p->servers;
592 memcpy(rad, buf, len);
598 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
599 int loc, i, l, n, r = 0;
602 STACK_OF(GENERAL_NAME) *alt;
605 debug(DBG_DBG, "subjectaltnameaddr");
607 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
611 ex = X509_get_ext(cert, loc);
612 alt = X509V3_EXT_d2i(ex);
616 n = sk_GENERAL_NAME_num(alt);
617 for (i = 0; i < n; i++) {
618 gn = sk_GENERAL_NAME_value(alt, i);
619 if (gn->type != GEN_IPADD)
622 v = (char *)ASN1_STRING_data(gn->d.ia5);
623 l = ASN1_STRING_length(gn->d.ia5);
624 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
625 && !memcmp(v, &addr, l)) {
630 GENERAL_NAMES_free(alt);
634 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
641 nm = X509_get_subject_name(cert);
644 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
647 e = X509_NAME_get_entry(nm, loc);
648 t = X509_NAME_ENTRY_get_data(e);
649 v = (char *) ASN1_STRING_data(t);
650 l = ASN1_STRING_length(t);
654 if (l == strlen(exact) && !strncasecmp(exact, v, l))
657 s = stringcopy((char *)v, l);
659 debug(DBG_ERR, "malloc failed");
662 if (regexec(regex, s, 0, NULL, 0)) {
673 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
674 int loc, i, l, n, r = 0;
677 STACK_OF(GENERAL_NAME) *alt;
680 debug(DBG_DBG, "subjectaltnameregexp");
682 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
686 ex = X509_get_ext(cert, loc);
687 alt = X509V3_EXT_d2i(ex);
691 n = sk_GENERAL_NAME_num(alt);
692 for (i = 0; i < n; i++) {
693 gn = sk_GENERAL_NAME_value(alt, i);
694 if (gn->type != type)
697 v = (char *)ASN1_STRING_data(gn->d.ia5);
698 l = ASN1_STRING_length(gn->d.ia5);
702 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
705 if (memcmp(v, exact, l))
708 s = stringcopy((char *)v, l);
710 debug(DBG_ERR, "malloc failed");
713 if (regexec(regex, s, 0, NULL, 0)) {
722 GENERAL_NAMES_free(alt);
726 int tlsverifycert(SSL *ssl, struct clsrvconf *conf) {
729 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
731 struct in6_addr addr;
733 if (SSL_get_verify_result(ssl) != X509_V_OK) {
734 debug(DBG_ERR, "tlsverifycert: basic validation failed");
735 while ((error = ERR_get_error()))
736 debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
740 cert = SSL_get_peer_certificate(ssl);
742 debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
746 if (conf->prefixlen == 255) {
747 if (inet_pton(AF_INET, conf->host, &addr))
749 else if (inet_pton(AF_INET6, conf->host, &addr))
752 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
755 debug(DBG_DBG, "tlsverifycert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
758 debug(DBG_DBG, "tlsverifycert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
760 if (!cnregexp(cert, conf->host, NULL)) {
761 debug(DBG_ERR, "tlsverifycert: cn not matching host %s", conf->host);
764 debug(DBG_DBG, "tlsverifycert: Found cn matching host %s", conf->host);
767 if (conf->certcnregex) {
768 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
769 debug(DBG_DBG, "tlsverifycert: CN not matching regex");
772 debug(DBG_DBG, "tlsverifycert: CN matching regex");
774 if (conf->certuriregex) {
775 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
776 debug(DBG_DBG, "tlsverifycert: subjectaltname URI not matching regex");
779 debug(DBG_DBG, "tlsverifycert: subjectaltname URI matching regex");
789 void tlsconnect(struct server *server, struct timeval *when, char *text) {
793 debug(DBG_DBG, "tlsconnect called from %s", text);
794 pthread_mutex_lock(&server->lock);
795 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
796 /* already reconnected, nothing to do */
797 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
798 pthread_mutex_unlock(&server->lock);
802 debug(DBG_DBG, "tlsconnect %s", text);
805 gettimeofday(&now, NULL);
806 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
807 if (server->connectionok) {
808 server->connectionok = 0;
810 } else if (elapsed < 5)
812 else if (elapsed < 300) {
813 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
815 } else if (elapsed < 100000) {
816 debug(DBG_INFO, "tlsconnect: sleeping %ds", 600);
819 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
820 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
821 if (server->sock >= 0)
823 if ((server->sock = connecttcp(server->conf->addrinfo)) < 0) {
824 debug(DBG_ERR, "tlsconnect: connecttcp failed");
828 SSL_free(server->ssl);
829 server->ssl = SSL_new(server->conf->ssl_ctx);
830 SSL_set_fd(server->ssl, server->sock);
831 if (SSL_connect(server->ssl) > 0 && tlsverifycert(server->ssl, server->conf))
834 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
835 gettimeofday(&server->lastconnecttry, NULL);
836 pthread_mutex_unlock(&server->lock);
839 unsigned char *radtlsget(SSL *ssl) {
841 unsigned char buf[4], *rad;
844 for (total = 0; total < 4; total += cnt) {
845 cnt = SSL_read(ssl, buf + total, 4 - total);
847 debug(DBG_ERR, "radtlsget: connection lost");
848 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
849 /* remote end sent close_notify, send one back */
859 debug(DBG_ERR, "radtlsget: malloc failed");
864 for (; total < len; total += cnt) {
865 cnt = SSL_read(ssl, rad + total, len - total);
867 debug(DBG_ERR, "radtlsget: connection lost");
868 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
869 /* remote end sent close_notify, send one back */
881 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
884 debug(DBG_DBG, "radtlsget: got %d bytes", total);
888 int clientradput(struct server *server, unsigned char *rad) {
892 struct timeval lastconnecttry;
893 struct clsrvconf *conf = server->conf;
896 if (conf->type == 'U') {
897 if (sendto(server->sock, rad, len, 0, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen) >= 0) {
898 debug(DBG_DBG, "clienradput: sent UDP of length %d to %s port %s", len, conf->host, conf->port);
901 debug(DBG_WARN, "clientradput: send failed");
905 lastconnecttry = server->lastconnecttry;
906 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
907 while ((error = ERR_get_error()))
908 debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
909 tlsconnect(server, &lastconnecttry, "clientradput");
910 lastconnecttry = server->lastconnecttry;
913 server->connectionok = 1;
914 debug(DBG_DBG, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
918 int radsign(unsigned char *rad, unsigned char *sec) {
919 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
920 static unsigned char first = 1;
921 static EVP_MD_CTX mdctx;
925 pthread_mutex_lock(&lock);
927 EVP_MD_CTX_init(&mdctx);
931 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
932 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
933 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
934 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
936 pthread_mutex_unlock(&lock);
940 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
941 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
942 static unsigned char first = 1;
943 static EVP_MD_CTX mdctx;
944 unsigned char hash[EVP_MAX_MD_SIZE];
948 pthread_mutex_lock(&lock);
950 EVP_MD_CTX_init(&mdctx);
956 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
957 EVP_DigestUpdate(&mdctx, rad, 4) &&
958 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
959 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
960 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
961 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
963 !memcmp(hash, rad + 4, 16));
964 pthread_mutex_unlock(&lock);
968 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
969 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
970 static unsigned char first = 1;
971 static HMAC_CTX hmacctx;
973 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
975 pthread_mutex_lock(&lock);
977 HMAC_CTX_init(&hmacctx);
981 memcpy(auth, authattr, 16);
982 memset(authattr, 0, 16);
984 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
985 HMAC_Update(&hmacctx, rad, RADLEN(rad));
986 HMAC_Final(&hmacctx, hash, &md_len);
987 memcpy(authattr, auth, 16);
989 debug(DBG_WARN, "message auth computation failed");
990 pthread_mutex_unlock(&lock);
994 if (memcmp(auth, hash, 16)) {
995 debug(DBG_WARN, "message authenticator, wrong value");
996 pthread_mutex_unlock(&lock);
1000 pthread_mutex_unlock(&lock);
1004 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
1005 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1006 static unsigned char first = 1;
1007 static HMAC_CTX hmacctx;
1008 unsigned int md_len;
1013 pthread_mutex_lock(&lock);
1015 HMAC_CTX_init(&hmacctx);
1019 memset(authattrval, 0, 16);
1021 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1022 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1023 HMAC_Final(&hmacctx, authattrval, &md_len);
1025 debug(DBG_WARN, "message auth computation failed");
1026 pthread_mutex_unlock(&lock);
1030 pthread_mutex_unlock(&lock);
1034 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
1035 while (length > 1) {
1036 if (ATTRTYPE(attrs) == type)
1038 length -= ATTRLEN(attrs);
1039 attrs += ATTRLEN(attrs);
1044 void freerqdata(struct request *rq) {
1045 if (rq->origusername)
1046 free(rq->origusername);
1051 void sendrq(struct server *to, struct request *rq) {
1055 pthread_mutex_lock(&to->newrq_mutex);
1056 /* might simplify if only try nextid, might be ok */
1057 for (i = to->nextid; i < MAX_REQUESTS; i++)
1058 if (!to->requests[i].buf)
1060 if (i == MAX_REQUESTS) {
1061 for (i = 0; i < to->nextid; i++)
1062 if (!to->requests[i].buf)
1064 if (i == to->nextid) {
1065 debug(DBG_WARN, "No room in queue, dropping request");
1067 pthread_mutex_unlock(&to->newrq_mutex);
1072 rq->buf[1] = (char)i;
1074 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1075 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1077 pthread_mutex_unlock(&to->newrq_mutex);
1081 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1082 to->requests[i] = *rq;
1087 debug(DBG_DBG, "signalling client writer");
1088 pthread_cond_signal(&to->newrq_cond);
1090 pthread_mutex_unlock(&to->newrq_mutex);
1093 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
1094 struct reply *reply;
1097 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1099 debug(DBG_WARN, "sendreply: failed to sign message");
1103 reply = malloc(sizeof(struct reply));
1106 debug(DBG_ERR, "sendreply: malloc failed");
1109 memset(reply, 0, sizeof(struct reply));
1112 reply->tosa = *tosa;
1114 pthread_mutex_lock(&to->replyq->mutex);
1116 first = list_first(to->replyq->replies) == NULL;
1118 if (!list_push(to->replyq->replies, reply)) {
1119 pthread_mutex_unlock(&to->replyq->mutex);
1122 debug(DBG_ERR, "sendreply: malloc failed");
1127 debug(DBG_DBG, "signalling server writer");
1128 pthread_cond_signal(&to->replyq->cond);
1130 pthread_mutex_unlock(&to->replyq->mutex);
1133 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1134 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1135 static unsigned char first = 1;
1136 static EVP_MD_CTX mdctx;
1137 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1138 unsigned int md_len;
1139 uint8_t i, offset = 0, out[128];
1141 pthread_mutex_lock(&lock);
1143 EVP_MD_CTX_init(&mdctx);
1149 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1150 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1151 !EVP_DigestUpdate(&mdctx, input, 16) ||
1152 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1154 pthread_mutex_unlock(&lock);
1157 for (i = 0; i < 16; i++)
1158 out[offset + i] = hash[i] ^ in[offset + i];
1159 input = out + offset - 16;
1164 memcpy(in, out, len);
1165 pthread_mutex_unlock(&lock);
1169 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1170 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1171 static unsigned char first = 1;
1172 static EVP_MD_CTX mdctx;
1173 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1174 unsigned int md_len;
1175 uint8_t i, offset = 0, out[128];
1177 pthread_mutex_lock(&lock);
1179 EVP_MD_CTX_init(&mdctx);
1185 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1186 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1187 !EVP_DigestUpdate(&mdctx, input, 16) ||
1188 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1190 pthread_mutex_unlock(&lock);
1193 for (i = 0; i < 16; i++)
1194 out[offset + i] = hash[i] ^ in[offset + i];
1195 input = in + offset;
1200 memcpy(in, out, len);
1201 pthread_mutex_unlock(&lock);
1205 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1206 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1207 static unsigned char first = 1;
1208 static EVP_MD_CTX mdctx;
1209 unsigned char hash[EVP_MAX_MD_SIZE];
1210 unsigned int md_len;
1213 pthread_mutex_lock(&lock);
1215 EVP_MD_CTX_init(&mdctx);
1220 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1221 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1222 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1225 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1226 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1227 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1228 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1229 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1230 pthread_mutex_unlock(&lock);
1235 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1238 for (i = 0; i < 16; i++)
1241 for (offset = 16; offset < len; offset += 16) {
1243 printf("text + offset - 16 c(%d): ", offset / 16);
1244 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1246 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1247 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1248 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1249 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1251 pthread_mutex_unlock(&lock);
1255 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1258 for (i = 0; i < 16; i++)
1259 text[offset + i] ^= hash[i];
1263 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1266 pthread_mutex_unlock(&lock);
1270 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1271 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1272 static unsigned char first = 1;
1273 static EVP_MD_CTX mdctx;
1274 unsigned char hash[EVP_MAX_MD_SIZE];
1275 unsigned int md_len;
1279 pthread_mutex_lock(&lock);
1281 EVP_MD_CTX_init(&mdctx);
1286 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1287 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1288 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1291 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1292 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1293 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1294 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1295 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1296 pthread_mutex_unlock(&lock);
1301 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1304 for (i = 0; i < 16; i++)
1305 plain[i] = text[i] ^ hash[i];
1307 for (offset = 16; offset < len; offset += 16) {
1309 printf("text + offset - 16 c(%d): ", offset / 16);
1310 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1312 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1313 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1314 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1315 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1317 pthread_mutex_unlock(&lock);
1321 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1324 for (i = 0; i < 16; i++)
1325 plain[offset + i] = text[offset + i] ^ hash[i];
1328 memcpy(text, plain, len);
1330 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1333 pthread_mutex_unlock(&lock);
1337 struct realm *id2realm(char *id, uint8_t len) {
1338 struct list_node *entry;
1339 struct realm *realm;
1341 for (entry = list_first(realms); entry; entry = list_next(entry)) {
1342 realm = (struct realm *)entry->data;
1343 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1344 debug(DBG_DBG, "found matching realm: %s", realm->name);
1351 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
1354 pthread_mutex_lock(&to->newrq_mutex);
1355 for (i = 0; i < MAX_REQUESTS; i++)
1356 if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
1358 pthread_mutex_unlock(&to->newrq_mutex);
1360 return i < MAX_REQUESTS;
1363 int attrvalidate(unsigned char *attrs, int length) {
1364 while (length > 1) {
1365 if (ATTRLEN(attrs) < 2) {
1366 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1369 length -= ATTRLEN(attrs);
1371 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1374 attrs += ATTRLEN(attrs);
1377 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1381 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1382 if (len < 16 || len > 128 || len % 16) {
1383 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1387 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1388 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1392 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1394 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1395 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1401 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1404 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1405 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1408 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1409 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1415 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1416 char *oldsecret, char *newsecret) {
1417 unsigned char *attr;
1419 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1420 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1421 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1427 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1431 for (; attrs[0]; attrs += 2)
1432 if (attrs[0] == vendor && attrs[1] == subattr)
1437 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1438 uint8_t alen, sublen, rmlen = 0;
1439 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1442 if (!removevendorattrs)
1445 while (*removevendorattrs && *removevendorattrs != vendor)
1446 removevendorattrs += 2;
1447 if (!*removevendorattrs)
1450 alen = ATTRLEN(attrs);
1452 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1453 /* remove entire vendor attribute */
1454 memmove(attrs, attrs + alen, length - alen);
1459 subattrs = ATTRVAL(attrs) + 4;
1461 if (!attrvalidate(subattrs, sublen)) {
1462 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1467 while (sublen > 1) {
1468 alen = ATTRLEN(subattrs);
1471 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1472 memmove(subattrs, subattrs + alen, length);
1478 ATTRLEN(attrs) -= rmlen;
1482 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1483 uint8_t *attrs, alen;
1484 uint16_t len, rmlen = 0;
1486 if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1489 len = RADLEN(buf) - 20;
1492 alen = ATTRLEN(attrs);
1494 if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1495 memmove(attrs, attrs + alen, len);
1497 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1498 rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1503 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1506 /* returns a pointer to the resized attribute value */
1507 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1508 uint8_t *attrs, *attr, vallen;
1512 len = RADLEN(*buf) - 20;
1515 attr = attrget(attrs, len, type);
1519 vallen = ATTRVALLEN(attr);
1520 if (vallen == newvallen)
1523 len += newvallen - vallen;
1524 if (newvallen > vallen) {
1525 new = realloc(*buf, len + 20);
1527 debug(DBG_ERR, "resizeattr: malloc failed");
1536 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1537 attr[1] = newvallen + 2;
1538 ((uint16_t *)*buf)[1] = htons(len + 20);
1542 int rewriteusername(struct request *rq, char *in) {
1543 size_t nmatch = 10, reslen = 0, start = 0;
1544 regmatch_t pmatch[10], *pfield;
1546 unsigned char *result;
1547 char *out = rq->from->conf->rewriteattrreplacement;
1549 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1550 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1554 rq->origusername = stringcopy(in, 0);
1555 if (!rq->origusername)
1558 for (i = start; out[i]; i++) {
1559 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1560 pfield = &pmatch[out[i + 1] - '0'];
1561 if (pfield->rm_so >= 0) {
1562 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1568 reslen += i - start;
1570 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1576 for (i = start; out[i]; i++) {
1577 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1578 pfield = &pmatch[out[i + 1] - '0'];
1579 if (pfield->rm_so >= 0) {
1580 memcpy(result + reslen, out + start, i - start);
1581 reslen += i - start;
1582 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1583 reslen += pfield->rm_eo - pfield->rm_so;
1590 memcpy(result + reslen, out + start, i - start);
1591 reslen += i - start;
1592 memcpy(in, result, reslen);
1597 void acclog(unsigned char *attrs, int length, char *host) {
1598 unsigned char *attr;
1601 attr = attrget(attrs, length, RAD_Attr_User_Name);
1603 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1606 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1607 username[ATTRVALLEN(attr)] = '\0';
1608 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1611 void respondaccounting(struct request *rq) {
1612 unsigned char *resp;
1616 debug(DBG_ERR, "respondstatusserver: malloc failed");
1619 memcpy(resp, rq->buf, 20);
1620 resp[0] = RAD_Accounting_Response;
1623 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1624 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1627 void respondstatusserver(struct request *rq) {
1628 unsigned char *resp;
1632 debug(DBG_ERR, "respondstatusserver: malloc failed");
1635 memcpy(resp, rq->buf, 20);
1636 resp[0] = RAD_Access_Accept;
1639 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1640 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1643 void respondreject(struct request *rq, char *message) {
1644 unsigned char *resp;
1647 if (message && *message)
1648 len += 2 + strlen(message);
1652 debug(DBG_ERR, "respondreject: malloc failed");
1655 memcpy(resp, rq->buf, 20);
1656 resp[0] = RAD_Access_Reject;
1657 *(uint16_t *)(resp + 2) = htons(len);
1658 if (message && *message) {
1659 resp[20] = RAD_Attr_Reply_Message;
1660 resp[21] = len - 20;
1661 memcpy(resp + 22, message, len - 22);
1663 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1666 struct server *realm2server(struct realm *realm) {
1667 struct list_node *entry;
1668 struct server *server, *best = NULL;
1670 for (entry = list_first(realm->srvconfs); entry; entry = list_next(entry)) {
1671 server = ((struct clsrvconf *)entry->data)->servers;
1672 if (!server->connectionok)
1674 if (!server->loststatsrv)
1680 if (server->loststatsrv < best->loststatsrv)
1686 void radsrv(struct request *rq) {
1687 uint8_t code, id, *auth, *attrs, *attr;
1689 struct server *to = NULL;
1691 unsigned char newauth[16];
1692 struct realm *realm = NULL;
1694 code = *(uint8_t *)rq->buf;
1695 id = *(uint8_t *)(rq->buf + 1);
1696 len = RADLEN(rq->buf);
1697 auth = (uint8_t *)(rq->buf + 4);
1699 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1701 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1702 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1708 attrs = rq->buf + 20;
1710 if (!attrvalidate(attrs, len)) {
1711 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1716 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1717 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
1718 debug(DBG_WARN, "radsrv: message authentication failed");
1723 if (code != RAD_Access_Request) {
1725 case RAD_Accounting_Request:
1726 /* when forwarding accounting, also filter attributes, call removeattrs(rq) */
1727 acclog(attrs, len, rq->from->conf->host);
1728 respondaccounting(rq);
1730 case RAD_Status_Server:
1731 respondstatusserver(rq);
1738 /* code == RAD_Access_Request */
1739 if (rq->from->conf->rewrite) {
1740 dorewrite(rq->buf, rq->from->conf->rewrite);
1741 len = RADLEN(rq->buf) - 20;
1744 attr = attrget(attrs, len, RAD_Attr_User_Name);
1746 debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1750 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1751 username[ATTRVALLEN(attr)] = '\0';
1753 if (rq->from->conf->rewriteattrregex) {
1754 if (!rewriteusername(rq, username)) {
1755 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1759 len = RADLEN(rq->buf) - 20;
1760 auth = (uint8_t *)(rq->buf + 4);
1761 attrs = rq->buf + 20;
1764 if (rq->origusername)
1765 debug(DBG_DBG, "Access Request with username: %s (originally %s)", username, rq->origusername);
1767 debug(DBG_DBG, "Access Request with username: %s", username);
1769 realm = id2realm(username, strlen(username));
1771 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1776 to = realm2server(realm);
1777 if (to && rqinqueue(to, rq->from, id)) {
1778 debug(DBG_INFO, "radsrv: already got request from host %s with id %d, ignoring", rq->from->conf->host, id);
1784 if (realm->message) {
1785 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, username);
1786 respondreject(rq, realm->message);
1792 if (!RAND_bytes(newauth, 16)) {
1793 debug(DBG_WARN, "radsrv: failed to generate random auth");
1799 printfchars(NULL, "auth", "%02x ", auth, 16);
1802 attr = attrget(attrs, len, RAD_Attr_User_Password);
1804 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1805 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1811 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1813 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1814 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1821 memcpy(rq->origauth, auth, 16);
1822 memcpy(auth, newauth, 16);
1826 int replyh(struct server *server, unsigned char *buf) {
1827 struct client *from;
1830 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
1831 struct sockaddr_storage fromsa;
1834 server->connectionok = 1;
1835 server->loststatsrv = 0;
1837 i = buf[1]; /* i is the id */
1840 case RAD_Access_Accept:
1841 debug(DBG_DBG, "got Access Accept with id %d", i);
1843 case RAD_Access_Reject:
1844 debug(DBG_DBG, "got Access Reject with id %d", i);
1846 case RAD_Access_Challenge:
1847 debug(DBG_DBG, "got Access Challenge with id %d", i);
1850 debug(DBG_INFO, "replyh: discarding, only accept access accept, access reject and access challenge messages");
1854 rq = server->requests + i;
1856 pthread_mutex_lock(&server->newrq_mutex);
1857 if (!rq->buf || !rq->tries) {
1858 pthread_mutex_unlock(&server->newrq_mutex);
1859 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
1864 pthread_mutex_unlock(&server->newrq_mutex);
1865 debug(DBG_INFO, "replyh: already received, ignoring reply");
1869 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
1870 pthread_mutex_unlock(&server->newrq_mutex);
1871 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
1875 len = RADLEN(buf) - 20;
1878 if (!attrvalidate(attrs, len)) {
1879 pthread_mutex_unlock(&server->newrq_mutex);
1880 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
1884 /* Message Authenticator */
1885 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1887 if (ATTRVALLEN(messageauth) != 16) {
1888 pthread_mutex_unlock(&server->newrq_mutex);
1889 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
1892 memcpy(tmp, buf + 4, 16);
1893 memcpy(buf + 4, rq->buf + 4, 16);
1894 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
1895 pthread_mutex_unlock(&server->newrq_mutex);
1896 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
1899 memcpy(buf + 4, tmp, 16);
1900 debug(DBG_DBG, "replyh: message auth ok");
1903 if (*rq->buf == RAD_Status_Server) {
1905 pthread_mutex_unlock(&server->newrq_mutex);
1906 debug(DBG_INFO, "replyh: got status server response from %s", server->conf->host);
1912 pthread_mutex_unlock(&server->newrq_mutex);
1913 debug(DBG_INFO, "replyh: client gone, ignoring reply");
1917 if (server->conf->rewrite) {
1918 dorewrite(buf, server->conf->rewrite);
1919 len = RADLEN(buf) - 20;
1923 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1924 if (ATTRVALLEN(attr) <= 4)
1927 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
1930 sublen = ATTRVALLEN(attr) - 4;
1931 subattrs = ATTRVAL(attr) + 4;
1932 if (!attrvalidate(subattrs, sublen) ||
1933 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1934 rq, server->conf->secret, from->conf->secret) ||
1935 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1936 rq, server->conf->secret, from->conf->secret))
1940 pthread_mutex_unlock(&server->newrq_mutex);
1941 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1945 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject) {
1946 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
1947 /* we know the attribute exists */
1948 memcpy(tmp, ATTRVAL(attr), ATTRVALLEN(attr));
1949 tmp[ATTRVALLEN(attr)] = '\0';
1951 case RAD_Access_Accept:
1952 if (rq->origusername)
1953 debug(DBG_INFO, "Access Accept for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1955 debug(DBG_INFO, "Access Accept for %s from %s", tmp, server->conf->host);
1957 case RAD_Access_Reject:
1958 if (rq->origusername)
1959 debug(DBG_INFO, "Access Reject for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1961 debug(DBG_INFO, "Access Reject for %s from %s", tmp, server->conf->host);
1966 buf[1] = (char)rq->origid;
1967 memcpy(buf + 4, rq->origauth, 16);
1969 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1972 if (rq->origusername) {
1973 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
1975 pthread_mutex_unlock(&server->newrq_mutex);
1976 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1979 memcpy(username, rq->origusername, strlen(rq->origusername));
1980 len = RADLEN(buf) - 20;
1983 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1987 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
1988 pthread_mutex_unlock(&server->newrq_mutex);
1989 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
1992 debug(DBG_DBG, "replyh: computed messageauthattr");
1995 if (from->conf->type == 'U')
1996 fromsa = rq->fromsa;
1997 /* once we set received = 1, rq may be reused */
2000 debug(DBG_DBG, "replyh: giving packet back to where it came from");
2001 sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
2002 pthread_mutex_unlock(&server->newrq_mutex);
2006 void *udpclientrd(void *arg) {
2007 struct server *server;
2009 int *s = (int *)arg;
2013 buf = radudpget(*s, NULL, &server, NULL);
2014 if (!replyh(server, buf))
2019 void *tlsclientrd(void *arg) {
2020 struct server *server = (struct server *)arg;
2022 struct timeval lastconnecttry;
2025 /* yes, lastconnecttry is really necessary */
2026 lastconnecttry = server->lastconnecttry;
2027 buf = radtlsget(server->ssl);
2029 tlsconnect(server, &lastconnecttry, "clientrd");
2033 if (!replyh(server, buf))
2038 void *clientwr(void *arg) {
2039 struct server *server = (struct server *)arg;
2041 pthread_t tlsclientrdth;
2044 struct timeval now, lastsend;
2045 struct timespec timeout;
2046 struct request statsrvrq;
2047 unsigned char statsrvbuf[38];
2049 memset(&timeout, 0, sizeof(struct timespec));
2051 if (server->conf->statusserver) {
2052 memset(&statsrvrq, 0, sizeof(struct request));
2053 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2054 statsrvbuf[0] = RAD_Status_Server;
2056 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2057 statsrvbuf[21] = 18;
2058 gettimeofday(&lastsend, NULL);
2061 if (server->conf->type == 'U') {
2062 server->connectionok = 1;
2064 tlsconnect(server, NULL, "new client");
2065 server->connectionok = 1;
2066 if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server))
2067 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
2071 pthread_mutex_lock(&server->newrq_mutex);
2072 if (!server->newrq) {
2073 gettimeofday(&now, NULL);
2074 if (server->conf->statusserver) {
2075 /* random 0-7 seconds */
2076 RAND_bytes(&rnd, 1);
2078 if (!timeout.tv_sec || timeout.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
2079 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
2081 if (timeout.tv_sec) {
2082 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2083 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2086 debug(DBG_DBG, "clientwr: waiting for new request");
2087 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
2090 if (server->newrq) {
2091 debug(DBG_DBG, "clientwr: got new request");
2094 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2095 pthread_mutex_unlock(&server->newrq_mutex);
2097 for (i = 0; i < MAX_REQUESTS; i++) {
2098 pthread_mutex_lock(&server->newrq_mutex);
2099 while (i < MAX_REQUESTS && !server->requests[i].buf)
2101 if (i == MAX_REQUESTS) {
2102 pthread_mutex_unlock(&server->newrq_mutex);
2105 rq = server->requests + i;
2108 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2110 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2112 /* setting this to NULL means that it can be reused */
2115 pthread_mutex_unlock(&server->newrq_mutex);
2119 gettimeofday(&now, NULL);
2120 if (now.tv_sec < rq->expiry.tv_sec) {
2121 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2122 timeout.tv_sec = rq->expiry.tv_sec;
2123 pthread_mutex_unlock(&server->newrq_mutex);
2127 if (rq->tries == (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
2128 ? 1 : REQUEST_RETRIES)) {
2129 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2130 if (*rq->buf == RAD_Status_Server) {
2131 debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->conf->host);
2132 if (server->loststatsrv < 255)
2133 server->loststatsrv++;
2136 /* setting this to NULL means that it can be reused */
2138 pthread_mutex_unlock(&server->newrq_mutex);
2141 pthread_mutex_unlock(&server->newrq_mutex);
2143 rq->expiry.tv_sec = now.tv_sec +
2144 (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
2145 ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
2146 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2147 timeout.tv_sec = rq->expiry.tv_sec;
2149 clientradput(server, server->requests[i].buf);
2150 gettimeofday(&lastsend, NULL);
2152 if (server->conf->statusserver) {
2153 gettimeofday(&now, NULL);
2154 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
2155 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2156 debug(DBG_WARN, "clientwr: failed to generate random auth");
2159 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2160 if (!statsrvrq.buf) {
2161 debug(DBG_ERR, "clientwr: malloc failed");
2164 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2165 debug(DBG_DBG, "clientwr: sending status server to %s", server->conf->host);
2166 lastsend.tv_sec = now.tv_sec;
2167 sendrq(server, &statsrvrq);
2173 void *udpserverwr(void *arg) {
2174 struct replyq *replyq = udp_server_replyq;
2175 struct reply *reply;
2178 pthread_mutex_lock(&replyq->mutex);
2179 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2180 debug(DBG_DBG, "udp server writer, waiting for signal");
2181 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2182 debug(DBG_DBG, "udp server writer, got signal");
2184 pthread_mutex_unlock(&replyq->mutex);
2186 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
2187 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2188 debug(DBG_WARN, "sendudp: send failed");
2194 void *udpserverrd(void *arg) {
2196 pthread_t udpserverwrth;
2197 struct clsrvconf *listenres;
2199 listenres = resolve_hostport('U', options.listenudp, DEFAULT_UDP_PORT);
2200 if ((udp_server_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2201 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2203 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
2204 listenres->host ? listenres->host : "*", listenres->port);
2207 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
2208 debugx(1, DBG_ERR, "pthread_create failed");
2211 memset(&rq, 0, sizeof(struct request));
2212 rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
2217 void *udpaccserverrd(void *arg) {
2219 struct clsrvconf *listenres;
2221 listenres = resolve_hostport('U', options.listenaccudp, DEFAULT_UDP_PORT);
2222 if ((udp_accserver_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2223 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2225 debug(DBG_WARN, "udpaccserverrd: listening for UDP on %s:%s",
2226 listenres->host ? listenres->host : "*", listenres->port);
2230 memset(&rq, 0, sizeof(struct request));
2231 rq.buf = radudpget(udp_accserver_sock, &rq.from, NULL, &rq.fromsa);
2232 if (*(uint8_t *)rq.buf == RAD_Accounting_Request) {
2236 debug(DBG_INFO, "udpaccserverrd: got something other than accounting-request, ignoring");
2241 void *tlsserverwr(void *arg) {
2243 unsigned long error;
2244 struct client *client = (struct client *)arg;
2245 struct replyq *replyq;
2246 struct reply *reply;
2248 debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
2249 replyq = client->replyq;
2251 pthread_mutex_lock(&replyq->mutex);
2252 while (!list_first(replyq->replies)) {
2254 debug(DBG_DBG, "tls server writer, waiting for signal");
2255 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2256 debug(DBG_DBG, "tls server writer, got signal");
2259 /* ssl might have changed while waiting */
2260 pthread_mutex_unlock(&replyq->mutex);
2261 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2265 reply = (struct reply *)list_shift(replyq->replies);
2266 pthread_mutex_unlock(&replyq->mutex);
2267 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2269 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
2270 cnt, RADLEN(reply->buf));
2272 while ((error = ERR_get_error()))
2273 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2279 void *tlsserverrd(void *arg) {
2281 unsigned long error;
2283 struct client *client = (struct client *)arg;
2284 pthread_t tlsserverwrth;
2287 debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2290 if (SSL_accept(ssl) <= 0) {
2291 while ((error = ERR_get_error()))
2292 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2293 debug(DBG_ERR, "SSL_accept failed");
2296 if (tlsverifycert(client->ssl, client->conf)) {
2297 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2298 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2302 memset(&rq, 0, sizeof(struct request));
2303 rq.buf = radtlsget(client->ssl);
2306 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2310 debug(DBG_ERR, "tlsserverrd: connection lost");
2311 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2313 pthread_mutex_lock(&client->replyq->mutex);
2314 pthread_cond_signal(&client->replyq->cond);
2315 pthread_mutex_unlock(&client->replyq->mutex);
2316 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2317 pthread_join(tlsserverwrth, NULL);
2321 s = SSL_get_fd(ssl);
2323 shutdown(s, SHUT_RDWR);
2325 debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->conf->host);
2326 removeclientrqs(client);
2327 removeclient(client);
2332 pthread_t tlsserverth;
2334 struct sockaddr_storage from;
2335 size_t fromlen = sizeof(from);
2336 struct clsrvconf *conf;
2337 struct client *client;
2338 struct clsrvconf *listenres;
2340 listenres = resolve_hostport('T', options.listentcp, DEFAULT_TLS_PORT);
2341 if ((s = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2342 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
2345 debug(DBG_WARN, "listening for incoming TCP on %s:%s", listenres->host ? listenres->host : "*", listenres->port);
2349 snew = accept(s, (struct sockaddr *)&from, &fromlen);
2351 debug(DBG_WARN, "accept failed");
2354 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2356 conf = find_conf('T', (struct sockaddr *)&from, clconfs, NULL);
2358 debug(DBG_WARN, "ignoring request, not a known TLS client");
2359 shutdown(snew, SHUT_RDWR);
2364 client = addclient(conf);
2367 debug(DBG_WARN, "Failed to create new client instance");
2368 shutdown(snew, SHUT_RDWR);
2372 client->ssl = SSL_new(client->conf->ssl_ctx);
2373 SSL_set_fd(client->ssl, snew);
2374 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
2375 debug(DBG_ERR, "tlslistener: pthread_create failed");
2376 SSL_free(client->ssl);
2377 removeclient(client);
2378 shutdown(snew, SHUT_RDWR);
2382 pthread_detach(tlsserverth);
2387 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
2390 STACK_OF(X509_NAME) *calist;
2392 unsigned long error;
2394 if (!certfile || !certkeyfile)
2395 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2397 if (!cacertfile && !cacertpath)
2398 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2401 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2402 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2403 for (i = 0; i < CRYPTO_num_locks(); i++) {
2404 ssl_lock_count[i] = 0;
2405 pthread_mutex_init(&ssl_locks[i], NULL);
2407 CRYPTO_set_id_callback(ssl_thread_id);
2408 CRYPTO_set_locking_callback(ssl_locking_callback);
2410 SSL_load_error_strings();
2413 while (!RAND_status()) {
2414 time_t t = time(NULL);
2415 pid_t pid = getpid();
2416 RAND_seed((unsigned char *)&t, sizeof(time_t));
2417 RAND_seed((unsigned char *)&pid, sizeof(pid));
2420 ctx = SSL_CTX_new(TLSv1_method());
2422 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2423 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2425 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2426 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2427 !SSL_CTX_check_private_key(ctx) ||
2428 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2429 while ((error = ERR_get_error()))
2430 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2431 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2434 calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
2435 if (!cacertfile || calist) {
2438 calist = sk_X509_NAME_new_null();
2439 if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
2440 sk_X509_NAME_free(calist);
2446 while ((error = ERR_get_error()))
2447 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2448 debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
2450 SSL_CTX_set_client_CA_list(ctx, calist);
2452 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2453 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2455 new = malloc(sizeof(struct tls));
2456 if (!new || !list_push(tlsconfs, new))
2457 debugx(1, DBG_ERR, "malloc failed");
2459 memset(new, 0, sizeof(struct tls));
2460 new->name = stringcopy(value, 0);
2462 debugx(1, DBG_ERR, "malloc failed");
2465 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2469 struct list_node *entry;
2472 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2473 t = (struct tls *)entry->data;
2477 SSL_CTX_free(t->ctx);
2479 list_destroy(tlsconfs);
2483 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2484 struct list_node *entry;
2485 struct tls *t, *t1 = NULL, *t2 = NULL;
2487 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2488 t = (struct tls *)entry->data;
2489 if (!strcasecmp(t->name, alt1)) {
2493 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2504 void addrealm(char *value, char **servers, char *message) {
2506 struct realm *realm;
2507 char *s, *regex = NULL;
2508 struct list_node *entry;
2509 struct clsrvconf *conf;
2511 if (*value == '/') {
2512 /* regexp, remove optional trailing / if present */
2513 if (value[strlen(value) - 1] == '/')
2514 value[strlen(value) - 1] = '\0';
2516 /* not a regexp, let us make it one */
2517 if (*value == '*' && !value[1])
2518 regex = stringcopy(".*", 0);
2520 for (n = 0, s = value; *s;)
2523 regex = malloc(strlen(value) + n + 3);
2526 for (n = 1, s = value; *s; s++) {
2536 debugx(1, DBG_ERR, "malloc failed");
2537 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2540 realm = malloc(sizeof(struct realm));
2542 debugx(1, DBG_ERR, "malloc failed");
2544 memset(realm, 0, sizeof(struct realm));
2545 realm->name = stringcopy(value, 0);
2547 debugx(1, DBG_ERR, "malloc failed");
2548 if (message && strlen(message) > 253)
2549 debugx(1, DBG_ERR, "ReplyMessage can be at most 253 bytes");
2550 realm->message = message;
2552 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB))
2553 debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2557 if (servers && *servers) {
2558 realm->srvconfs = list_create();
2559 if (!realm->srvconfs)
2560 debugx(1, DBG_ERR, "malloc failed");
2561 for (n = 0; servers[n]; n++) {
2562 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2563 conf = (struct clsrvconf *)entry->data;
2564 if (!strcasecmp(servers[n], conf->name))
2568 debugx(1, DBG_ERR, "addrealm failed, no server %s", servers[n]);
2569 if (!list_push(realm->srvconfs, conf))
2570 debugx(1, DBG_ERR, "malloc failed");
2571 debug(DBG_DBG, "addrealm: added server %s for realm %s", conf->name, value);
2574 realm->srvconfs = NULL;
2576 if (!list_push(realms, realm))
2577 debugx(1, DBG_ERR, "malloc failed");
2578 debug(DBG_DBG, "addrealm: added realm %s", value);
2581 struct gconffile *openconfigfile(const char *filename) {
2583 char pathname[100], *base = NULL;
2584 struct gconffile *cf = NULL;
2586 f = pushgconffile(&cf, filename);
2588 debug(DBG_DBG, "reading config file %s", filename);
2592 if (strlen(filename) + 1 <= sizeof(pathname)) {
2593 /* basename() might modify the string */
2594 strcpy(pathname, filename);
2595 base = basename(pathname);
2596 f = pushgconffile(&cf, base);
2600 debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
2602 debug(DBG_DBG, "reading config file %s", base);
2606 int addmatchcertattr(struct clsrvconf *conf, char *matchcertattr) {
2610 if (strncasecmp(matchcertattr, "CN:/", 4)) {
2611 r = &conf->certcnregex;
2612 v = matchcertattr + 4;
2613 } else if (strncasecmp(matchcertattr, "SubjectAltName:URI:/", 20)) {
2614 r = &conf->certuriregex;
2615 v = matchcertattr + 20;
2620 /* regexp, remove optional trailing / if present */
2621 if (v[strlen(v) - 1] == '/')
2622 v[strlen(v) - 1] = '\0';
2626 *r = malloc(sizeof(regex_t));
2628 debug(DBG_ERR, "malloc failed");
2631 if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
2634 debug(DBG_ERR, "failed to compile regular expression %s", v);
2640 int addrewriteattr(struct clsrvconf *conf, char *rewriteattr) {
2643 v = rewriteattr + 11;
2644 if (strncasecmp(rewriteattr, "User-Name:/", 11) || !*v)
2646 /* regexp, remove optional trailing / if present */
2647 if (v[strlen(v) - 1] == '/')
2648 v[strlen(v) - 1] = '\0';
2656 conf->rewriteattrregex = malloc(sizeof(regex_t));
2657 if (!conf->rewriteattrregex) {
2658 debug(DBG_ERR, "malloc failed");
2662 conf->rewriteattrreplacement = stringcopy(w, 0);
2663 if (!conf->rewriteattrreplacement) {
2664 free(conf->rewriteattrregex);
2665 conf->rewriteattrregex = NULL;
2669 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
2670 free(conf->rewriteattrregex);
2671 conf->rewriteattrregex = NULL;
2672 free(conf->rewriteattrreplacement);
2673 conf->rewriteattrreplacement = NULL;
2674 debug(DBG_ERR, "failed to compile regular expression %s", v);
2681 /* should accept both names and numeric values, only numeric right now */
2682 uint8_t attrname2val(char *attrname) {
2685 val = atoi(attrname);
2686 return val > 0 && val < 256 ? val : 0;
2689 /* should accept both names and numeric values, only numeric right now */
2690 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2693 *vendor = atoi(attrname);
2694 s = strchr(attrname, ':');
2699 *type = atoi(s + 1);
2700 return *type >= 0 && *type < 256;
2703 void rewritefree() {
2704 struct list_node *entry;
2705 struct rewriteconf *r;
2707 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
2708 r = (struct rewriteconf *)entry->data;
2714 list_destroy(rewriteconfs);
2715 rewriteconfs = NULL;
2718 struct rewrite *getrewrite(char *alt1, char *alt2) {
2719 struct list_node *entry;
2720 struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
2722 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
2723 r = (struct rewriteconf *)entry->data;
2724 if (!strcasecmp(r->name, alt1)) {
2728 if (!r2 && alt2 && !strcasecmp(r->name, alt2))
2739 void addrewrite(char *value, char **attrs, char **vattrs) {
2740 struct rewriteconf *new;
2741 struct rewrite *rewrite = NULL;
2744 uint32_t *p, *va = NULL;
2748 for (; attrs[n]; n++);
2749 a = malloc((n + 1) * sizeof(uint8_t));
2751 debugx(1, DBG_ERR, "malloc failed");
2753 for (i = 0; i < n; i++)
2754 if (!(a[i] = attrname2val(attrs[i])))
2755 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
2761 for (; vattrs[n]; n++);
2762 va = malloc((2 * n + 1) * sizeof(uint32_t));
2764 debugx(1, DBG_ERR, "malloc failed");
2766 for (p = va, i = 0; i < n; i++, p += 2)
2767 if (!vattrname2val(vattrs[i], p, p + 1))
2768 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
2773 rewrite = malloc(sizeof(struct rewrite));
2775 debugx(1, DBG_ERR, "malloc failed");
2776 rewrite->removeattrs = a;
2777 rewrite->removevendorattrs = va;
2780 new = malloc(sizeof(struct rewriteconf));
2781 if (!new || !list_push(rewriteconfs, new))
2782 debugx(1, DBG_ERR, "malloc failed");
2784 memset(new, 0, sizeof(struct rewriteconf));
2785 new->name = stringcopy(value, 0);
2787 debugx(1, DBG_ERR, "malloc failed");
2789 new->rewrite = rewrite;
2790 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2793 void confclient_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2794 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *rewrite = NULL, *rewriteattr = NULL;
2795 struct clsrvconf *conf;
2797 debug(DBG_DBG, "confclient_cb called for %s", block);
2799 conf = malloc(sizeof(struct clsrvconf));
2800 if (!conf || !list_push(clconfs, conf))
2801 debugx(1, DBG_ERR, "malloc failed");
2802 memset(conf, 0, sizeof(struct clsrvconf));
2804 getgenericconfig(cf, block,
2805 "type", CONF_STR, &type,
2806 "host", CONF_STR, &conf->host,
2807 "secret", CONF_STR, &conf->secret,
2808 "tls", CONF_STR, &tls,
2809 "matchcertificateattribute", CONF_STR, &matchcertattr,
2810 "rewrite", CONF_STR, &rewrite,
2811 "rewriteattribute", CONF_STR, &rewriteattr,
2815 /* leave conf->name to be NULL for clients */
2817 conf->host = stringcopy(val, 0);
2819 if (type && !strcasecmp(type, "udp")) {
2822 } else if (type && !strcasecmp(type, "tls")) {
2823 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultclient", "default");
2825 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2826 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2827 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2831 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2836 free(matchcertattr);
2838 conf->rewrite = rewrite ? getrewrite(rewrite, NULL) : getrewrite("defaultclient", "default");
2841 if (!addrewriteattr(conf, rewriteattr))
2842 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2846 if (!resolvepeer(conf, 0))
2847 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2849 if (!conf->secret) {
2850 if (conf->type == 'U')
2851 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2852 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2856 void confserver_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2857 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *statusserver = NULL, *rewrite = NULL;
2858 struct clsrvconf *conf;
2860 debug(DBG_DBG, "confserver_cb called for %s", block);
2862 conf = malloc(sizeof(struct clsrvconf));
2863 if (!conf || !list_push(srvconfs, conf))
2864 debugx(1, DBG_ERR, "malloc failed");
2865 memset(conf, 0, sizeof(struct clsrvconf));
2867 getgenericconfig(cf, block,
2868 "type", CONF_STR, &type,
2869 "host", CONF_STR, &conf->host,
2870 "port", CONF_STR, &conf->port,
2871 "secret", CONF_STR, &conf->secret,
2872 "tls", CONF_STR, &tls,
2873 "matchcertificateattribute", CONF_STR, &matchcertattr,
2874 "rewrite", CONF_STR, &rewrite,
2875 "StatusServer", CONF_STR, &statusserver,
2879 conf->name = stringcopy(val, 0);
2881 conf->host = stringcopy(val, 0);
2883 if (type && !strcasecmp(type, "udp")) {
2887 conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
2888 } else if (type && !strcasecmp(type, "tls")) {
2889 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultserver", "default");
2891 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2892 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2893 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2895 conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
2899 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2904 free(matchcertattr);
2906 conf->rewrite = rewrite ? getrewrite(rewrite, NULL) : getrewrite("defaultserver", "default");
2908 if (!resolvepeer(conf, 0))
2909 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2911 if (!conf->secret) {
2912 if (conf->type == 'U')
2913 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2914 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2918 if (!strcasecmp(statusserver, "on"))
2919 conf->statusserver = 1;
2920 else if (strcasecmp(statusserver, "off"))
2921 debugx(1, DBG_ERR, "error in block %s, StatusServer is %s, must be on or off", block, statusserver);
2926 void confrealm_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2927 char **servers = NULL, *msg = NULL;
2929 debug(DBG_DBG, "confrealm_cb called for %s", block);
2931 getgenericconfig(cf, block,
2932 "server", CONF_MSTR, &servers,
2933 "ReplyMessage", CONF_STR, &msg,
2937 addrealm(val, servers, msg);
2941 void conftls_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2942 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
2944 debug(DBG_DBG, "conftls_cb called for %s", block);
2946 getgenericconfig(cf, block,
2947 "CACertificateFile", CONF_STR, &cacertfile,
2948 "CACertificatePath", CONF_STR, &cacertpath,
2949 "CertificateFile", CONF_STR, &certfile,
2950 "CertificateKeyFile", CONF_STR, &certkeyfile,
2951 "CertificateKeyPassword", CONF_STR, &certkeypwd,
2955 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
2963 void confrewrite_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2964 char **attrs = NULL, **vattrs = NULL;
2966 debug(DBG_DBG, "confrewrite_cb called for %s", block);
2968 getgenericconfig(cf, block,
2969 "removeAttribute", CONF_MSTR, &attrs,
2970 "removeVendorAttribute", CONF_MSTR, &vattrs,
2973 addrewrite(val, attrs, vattrs);
2978 void getmainconfig(const char *configfile) {
2979 char *loglevel = NULL;
2980 struct gconffile *cfs;
2982 cfs = openconfigfile(configfile);
2983 memset(&options, 0, sizeof(options));
2985 clconfs = list_create();
2987 debugx(1, DBG_ERR, "malloc failed");
2989 srvconfs = list_create();
2991 debugx(1, DBG_ERR, "malloc failed");
2993 realms = list_create();
2995 debugx(1, DBG_ERR, "malloc failed");
2997 tlsconfs = list_create();
2999 debugx(1, DBG_ERR, "malloc failed");
3001 rewriteconfs = list_create();
3003 debugx(1, DBG_ERR, "malloc failed");
3005 getgenericconfig(&cfs, NULL,
3006 "ListenUDP", CONF_STR, &options.listenudp,
3007 "ListenTCP", CONF_STR, &options.listentcp,
3008 "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
3009 "SourceUDP", CONF_STR, &options.sourceudp,
3010 "SourceTCP", CONF_STR, &options.sourcetcp,
3011 "LogLevel", CONF_STR, &loglevel,
3012 "LogDestination", CONF_STR, &options.logdestination,
3013 "Client", CONF_CBK, confclient_cb,
3014 "Server", CONF_CBK, confserver_cb,
3015 "Realm", CONF_CBK, confrealm_cb,
3016 "TLS", CONF_CBK, conftls_cb,
3017 "Rewrite", CONF_CBK, confrewrite_cb,
3025 if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
3026 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
3027 options.loglevel = *loglevel - '0';
3032 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3035 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3038 *configfile = optarg;
3041 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3042 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3043 *loglevel = *optarg - '0';
3052 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3057 if (!(argc - optind))
3061 debug(DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3066 int daemon(int a, int b) {
3074 for (i = 0; i < 3; i++) {
3076 open("/dev/null", O_RDWR);
3082 int main(int argc, char **argv) {
3083 pthread_t udpserverth, udpaccserverth, udpclient4rdth, udpclient6rdth;
3084 struct list_node *entry;
3085 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3086 char *configfile = NULL;
3088 debug_init("radsecproxy");
3089 debug_set_level(DEBUG_LEVEL);
3090 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3092 debug_set_level(loglevel);
3093 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3095 options.loglevel = loglevel;
3096 else if (options.loglevel)
3097 debug_set_level(options.loglevel);
3099 options.logdestination = NULL;
3101 if (!options.logdestination)
3102 options.logdestination = "x-syslog:///";
3103 debug_set_destination(options.logdestination);
3107 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3109 if (!list_first(clconfs))
3110 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3111 if (!list_first(srvconfs))
3112 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
3113 if (!list_first(realms))
3114 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3116 if (!foreground && (daemon(0, 0) < 0))
3117 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3119 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3121 if (client_udp_count) {
3122 udp_server_replyq = newreplyq();
3123 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
3124 debugx(1, DBG_ERR, "pthread_create failed");
3125 if (options.listenaccudp)
3126 if (pthread_create(&udpaccserverth, NULL, udpaccserverrd, NULL))
3127 debugx(1, DBG_ERR, "pthread_create failed");
3130 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3131 addserver((struct clsrvconf *)entry->data);
3132 if (pthread_create(&((struct clsrvconf *)entry->data)->servers->clientth, NULL, clientwr,
3133 (void *)((struct clsrvconf *)entry->data)->servers))
3134 debugx(1, DBG_ERR, "pthread_create failed");
3136 /* srcudpres no longer needed, while srctcpres is needed later */
3141 if (udp_client4_sock >= 0)
3142 if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
3143 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
3144 if (udp_client6_sock >= 0)
3145 if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
3146 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
3148 if (client_tls_count)
3149 return tlslistener();
3151 /* just hang around doing nothing, anything to do here? */