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 * TCP accounting not yet supported
34 * We are not removing client requests from dynamic servers, see removeclientrqs()
38 #include <sys/socket.h>
39 #include <netinet/in.h>
48 #include <sys/types.h>
49 #include <sys/select.h>
52 #include <arpa/inet.h>
56 #include <openssl/ssl.h>
57 #include <openssl/rand.h>
58 #include <openssl/err.h>
59 #include <openssl/md5.h>
60 #include <openssl/hmac.h>
61 #include <openssl/x509v3.h>
66 #include "radsecproxy.h"
68 static struct options options;
69 struct list *clconfs, *srvconfs, *realms, *tlsconfs, *rewriteconfs;
71 static struct addrinfo *srcprotores[4] = { NULL, NULL, NULL, NULL };
73 static struct queue *udp_server_replyq = NULL;
74 static int udp_client4_sock = -1;
75 static int udp_client6_sock = -1;
76 static int dtls_client4_sock = -1;
77 static int dtls_client6_sock = -1;
78 static pthread_mutex_t tlsconfs_lock;
79 static pthread_mutex_t *ssl_locks = NULL;
80 static long *ssl_lock_count;
84 /* minimum required declarations to avoid reordering code */
85 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
86 int dynamicconfig(struct server *server);
87 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
88 void freerealm(struct realm *realm);
89 void freeclsrvconf(struct clsrvconf *conf);
90 void freerqdata(struct request *rq);
91 void *udpserverrd(void *arg);
92 void *udpdtlsserverrd(void *arg);
93 void *tlslistener(void *arg);
94 void *tcplistener(void *arg);
95 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text);
96 int dtlsconnect(struct server *server, struct timeval *when, int timeout, char *text);
97 void *dtlsservernew(void *arg);
98 int tcpconnect(struct server *server, struct timeval *when, int timeout, char *text);
99 void *udpclientrd(void *arg);
100 void *tlsclientrd(void *arg);
101 void *dtlsclientrd(void *arg);
102 void *tcpclientrd(void *arg);
103 int clientradputudp(struct server *server, unsigned char *rad);
104 int clientradputtls(struct server *server, unsigned char *rad);
105 int clientradputdtls(struct server *server, unsigned char *rad);
106 int clientradputtcp(struct server *server, unsigned char *rad);
107 X509 *verifytlscert(SSL *ssl);
108 int radsrv(struct request *rq);
110 static const struct protodefs protodefs[] = {
111 { "udp", /* UDP, assuming RAD_UDP defined as 0 */
112 NULL, /* secretdefault */
113 SOCK_DGRAM, /* socktype */
114 "1812", /* portdefault */
115 REQUEST_RETRY_COUNT, /* retrycountdefault */
116 10, /* retrycountmax */
117 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
118 60, /* retryintervalmax */
119 udpserverrd, /* listener */
120 &options.sourceudp, /* srcaddrport */
121 NULL, /* connecter */
122 udpclientrd, /* clientreader */
123 clientradputudp /* clientradput */
125 { "tls", /* TLS, assuming RAD_TLS defined as 1 */
126 "mysecret", /* secretdefault */
127 SOCK_STREAM, /* socktype */
128 "2083", /* portdefault */
129 0, /* retrycountdefault */
130 0, /* retrycountmax */
131 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
132 60, /* retryintervalmax */
133 tlslistener, /* listener */
134 &options.sourcetls, /* srcaddrport */
135 tlsconnect, /* connecter */
136 tlsclientrd, /* clientreader */
137 clientradputtls /* clientradput */
139 { "tcp", /* TCP, assuming RAD_TCP defined as 2 */
140 NULL, /* secretdefault */
141 SOCK_STREAM, /* socktype */
142 "1812", /* portdefault */
143 0, /* retrycountdefault */
144 0, /* retrycountmax */
145 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
146 60, /* retryintervalmax */
147 tcplistener, /* listener */
148 &options.sourcetcp, /* srcaddrport */
149 tcpconnect, /* connecter */
150 tcpclientrd, /* clientreader */
151 clientradputtcp /* clientradput */
153 { "dtls", /* DTLS, assuming RAD_DTLS defined as 3 */
154 "mysecret", /* secretdefault */
155 SOCK_DGRAM, /* socktype */
156 "2083", /* portdefault */
157 REQUEST_RETRY_COUNT, /* retrycountdefault */
158 10, /* retrycountmax */
159 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
160 60, /* retryintervalmax */
161 udpdtlsserverrd, /* listener */
162 &options.sourcedtls, /* srcaddrport */
163 dtlsconnect, /* connecter */
164 dtlsclientrd, /* clientreader */
165 clientradputdtls /* clientradput */
171 uint8_t protoname2int(const char *name) {
174 for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
178 /* callbacks for making OpenSSL thread safe */
179 unsigned long ssl_thread_id() {
180 return (unsigned long)pthread_self();
183 void ssl_locking_callback(int mode, int type, const char *file, int line) {
184 if (mode & CRYPTO_LOCK) {
185 pthread_mutex_lock(&ssl_locks[type]);
186 ssl_lock_count[type]++;
188 pthread_mutex_unlock(&ssl_locks[type]);
191 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
192 int pwdlen = strlen(userdata);
193 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
195 memcpy(buf, userdata, pwdlen);
199 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
204 err_cert = X509_STORE_CTX_get_current_cert(ctx);
205 err = X509_STORE_CTX_get_error(ctx);
206 depth = X509_STORE_CTX_get_error_depth(ctx);
208 if (depth > MAX_CERT_DEPTH) {
210 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
211 X509_STORE_CTX_set_error(ctx, err);
215 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
216 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
219 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
220 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
221 debug(DBG_WARN, "\tIssuer=%s", buf);
223 case X509_V_ERR_CERT_NOT_YET_VALID:
224 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
225 debug(DBG_WARN, "\tCertificate not yet valid");
227 case X509_V_ERR_CERT_HAS_EXPIRED:
228 debug(DBG_WARN, "Certificate has expired");
230 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
231 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
236 printf("certificate verify returns %d\n", ok);
241 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
242 struct addrinfo hints, *addrinfo, *res;
246 slash = conf->host ? strchr(conf->host, '/') : NULL;
250 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
254 if (*s < '0' || *s > '9') {
255 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
258 plen = atoi(slash + 1);
259 if (plen < 0 || plen > 128) {
260 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
265 memset(&hints, 0, sizeof(hints));
266 hints.ai_socktype = conf->pdef->socktype;
267 hints.ai_family = AF_UNSPEC;
268 hints.ai_flags = ai_flags;
269 if (!conf->host && !conf->port) {
270 /* getaddrinfo() doesn't like host and port to be NULL */
271 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
272 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
275 for (res = addrinfo; res; res = res->ai_next) {
276 switch (res->ai_family) {
278 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
281 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
287 hints.ai_flags |= AI_NUMERICHOST;
288 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
289 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
294 switch (addrinfo->ai_family) {
297 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
298 freeaddrinfo(addrinfo);
305 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
306 freeaddrinfo(addrinfo);
309 conf->prefixlen = plen;
311 conf->prefixlen = 255;
314 freeaddrinfo(conf->addrinfo);
315 conf->addrinfo = addrinfo;
319 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
321 struct addrinfo *res;
323 for (res = addrinfo; res; res = res->ai_next) {
324 if (family != AF_UNSPEC && family != res->ai_family)
326 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
328 debug(DBG_WARN, "bindtoaddr: socket failed");
332 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
335 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
338 if (!bind(s, res->ai_addr, res->ai_addrlen))
340 debug(DBG_WARN, "bindtoaddr: bind failed");
346 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
351 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
355 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
357 debugx(1, DBG_ERR, "no ] matching initial [");
361 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
364 debugx(1, DBG_ERR, "missing host/address");
366 conf->host = stringcopy(field, p - field);
369 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
370 debugx(1, DBG_ERR, "unexpected character after ]");
373 /* port number or service name is specified */;
375 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
377 debugx(1, DBG_ERR, "syntax error, : but no following port");
378 conf->port = stringcopy(field, p - field);
380 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
384 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
385 struct clsrvconf *conf;
387 conf = malloc(sizeof(struct clsrvconf));
389 debugx(1, DBG_ERR, "malloc failed");
390 memset(conf, 0, sizeof(struct clsrvconf));
392 conf->pdef = &protodefs[conf->type];
394 parsehostport(lconf, conf, default_port);
395 if (!strcmp(conf->host, "*")) {
400 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
401 if (!resolvepeer(conf, AI_PASSIVE))
402 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
406 void freeclsrvres(struct clsrvconf *res) {
410 freeaddrinfo(res->addrinfo);
414 int connecttcp(struct addrinfo *addrinfo, struct addrinfo *src) {
416 struct addrinfo *res;
419 for (res = addrinfo; res; res = res->ai_next) {
420 s = bindtoaddr(src, res->ai_family, 1, 1);
422 debug(DBG_WARN, "connecttoserver: socket failed");
425 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
427 debug(DBG_WARN, "connecttoserver: connect failed");
434 /* returns 1 if the len first bits are equal, else 0 */
435 int prefixmatch(void *a1, void *a2, uint8_t len) {
436 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
438 if (l && memcmp(a1, a2, l))
443 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
446 /* returns next config with matching address, or NULL */
447 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
448 struct sockaddr_in6 *sa6 = NULL;
449 struct in_addr *a4 = NULL;
450 struct addrinfo *res;
451 struct list_node *entry;
452 struct clsrvconf *conf;
454 if (addr->sa_family == AF_INET6) {
455 sa6 = (struct sockaddr_in6 *)addr;
456 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
457 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
461 a4 = &((struct sockaddr_in *)addr)->sin_addr;
463 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
464 conf = (struct clsrvconf *)entry->data;
465 if (conf->type == type) {
466 if (conf->prefixlen == 255) {
467 for (res = conf->addrinfo; res; res = res->ai_next)
468 if ((a4 && res->ai_family == AF_INET &&
469 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
470 (sa6 && res->ai_family == AF_INET6 &&
471 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
477 res = conf->addrinfo;
479 ((a4 && res->ai_family == AF_INET &&
480 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
481 (sa6 && res->ai_family == AF_INET6 &&
482 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
493 /* returns next config of given type, or NULL */
494 struct clsrvconf *find_conf_type(uint8_t type, struct list *confs, struct list_node **cur) {
495 struct list_node *entry;
496 struct clsrvconf *conf;
498 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
499 conf = (struct clsrvconf *)entry->data;
500 if (conf->type == type) {
509 struct queue *newqueue() {
512 q = malloc(sizeof(struct queue));
514 debugx(1, DBG_ERR, "malloc failed");
515 q->entries = list_create();
517 debugx(1, DBG_ERR, "malloc failed");
518 pthread_mutex_init(&q->mutex, NULL);
519 pthread_cond_init(&q->cond, NULL);
523 void removequeue(struct queue *q) {
524 struct list_node *entry;
526 pthread_mutex_lock(&q->mutex);
527 for (entry = list_first(q->entries); entry; entry = list_next(entry))
528 free(((struct reply *)entry)->buf);
529 list_destroy(q->entries);
530 pthread_cond_destroy(&q->cond);
531 pthread_mutex_unlock(&q->mutex);
532 pthread_mutex_destroy(&q->mutex);
535 void freebios(struct queue *q) {
538 pthread_mutex_lock(&q->mutex);
539 while ((bio = (BIO *)list_shift(q->entries)))
541 pthread_mutex_unlock(&q->mutex);
545 struct client *addclient(struct clsrvconf *conf) {
546 struct client *new = malloc(sizeof(struct client));
549 debug(DBG_ERR, "malloc failed");
552 if (!conf->clients) {
553 conf->clients = list_create();
554 if (!conf->clients) {
555 debug(DBG_ERR, "malloc failed");
560 memset(new, 0, sizeof(struct client));
562 new->replyq = conf->type == RAD_UDP ? udp_server_replyq : newqueue();
563 if (conf->type == RAD_DTLS)
564 new->rbios = newqueue();
565 list_push(conf->clients, new);
569 void removeclient(struct client *client) {
570 if (!client || !client->conf->clients)
572 removequeue(client->replyq);
574 freebios(client->rbios);
575 list_removedata(client->conf->clients, client);
579 void removeclientrqs(struct client *client) {
580 struct list_node *entry;
581 struct server *server;
585 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
586 server = ((struct clsrvconf *)entry->data)->servers;
589 pthread_mutex_lock(&server->newrq_mutex);
590 for (i = 0; i < MAX_REQUESTS; i++) {
591 rq = server->requests + i;
592 if (rq->from == client)
595 pthread_mutex_unlock(&server->newrq_mutex);
599 void freeserver(struct server *server, uint8_t destroymutex) {
600 struct request *rq, *end;
605 if (server->requests) {
606 rq = server->requests;
607 for (end = rq + MAX_REQUESTS; rq < end; rq++)
609 free(server->requests);
612 freebios(server->rbios);
613 free(server->dynamiclookuparg);
615 pthread_mutex_destroy(&server->lock);
616 pthread_cond_destroy(&server->newrq_cond);
617 pthread_mutex_destroy(&server->newrq_mutex);
622 int addserver(struct clsrvconf *conf) {
623 struct clsrvconf *res;
627 debug(DBG_ERR, "addserver: currently works with just one server per conf");
630 conf->servers = malloc(sizeof(struct server));
631 if (!conf->servers) {
632 debug(DBG_ERR, "malloc failed");
635 memset(conf->servers, 0, sizeof(struct server));
636 conf->servers->conf = conf;
639 if (type == RAD_DTLS)
640 conf->servers->rbios = newqueue();
642 if (!srcprotores[type]) {
643 res = resolve_hostport(type, *conf->pdef->srcaddrport, NULL);
644 srcprotores[type] = res->addrinfo;
645 res->addrinfo = NULL;
651 switch (conf->addrinfo->ai_family) {
653 if (udp_client4_sock < 0) {
654 udp_client4_sock = bindtoaddr(srcprotores[RAD_UDP], AF_INET, 0, 1);
655 if (udp_client4_sock < 0)
656 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
658 conf->servers->sock = udp_client4_sock;
661 if (udp_client6_sock < 0) {
662 udp_client6_sock = bindtoaddr(srcprotores[RAD_UDP], AF_INET6, 0, 1);
663 if (udp_client6_sock < 0)
664 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
666 conf->servers->sock = udp_client6_sock;
669 debugx(1, DBG_ERR, "addserver: unsupported address family");
673 switch (conf->addrinfo->ai_family) {
675 if (dtls_client4_sock < 0) {
676 dtls_client4_sock = bindtoaddr(srcprotores[RAD_DTLS], AF_INET, 0, 1);
677 if (dtls_client4_sock < 0)
678 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
680 conf->servers->sock = dtls_client4_sock;
683 if (dtls_client6_sock < 0) {
684 dtls_client6_sock = bindtoaddr(srcprotores[RAD_DTLS], AF_INET6, 0, 1);
685 if (dtls_client6_sock < 0)
686 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
688 conf->servers->sock = dtls_client6_sock;
691 debugx(1, DBG_ERR, "addserver: unsupported address family");
695 conf->servers->sock = -1;
698 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
699 if (!conf->servers->requests) {
700 debug(DBG_ERR, "malloc failed");
703 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
704 debug(DBG_ERR, "mutex init failed");
707 conf->servers->newrq = 0;
708 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
709 debug(DBG_ERR, "mutex init failed");
710 pthread_mutex_destroy(&conf->servers->lock);
713 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
714 debug(DBG_ERR, "mutex init failed");
715 pthread_mutex_destroy(&conf->servers->newrq_mutex);
716 pthread_mutex_destroy(&conf->servers->lock);
723 freeserver(conf->servers, 0);
724 conf->servers = NULL;
728 int udp2bio(int s, struct queue *q, int cnt) {
738 debug(DBG_ERR, "udp2bio: malloc failed");
743 cnt = recv(s, buf, cnt, 0);
745 debug(DBG_WARN, "udp2bio: recv failed");
750 rbio = BIO_new_mem_buf(buf, cnt);
751 BIO_set_mem_eof_return(rbio, -1);
753 pthread_mutex_lock(&q->mutex);
754 if (!list_push(q->entries, rbio)) {
756 pthread_mutex_unlock(&q->mutex);
759 pthread_cond_signal(&q->cond);
760 pthread_mutex_unlock(&q->mutex);
764 /* exactly one of client and server must be non-NULL */
765 /* return who we received from in *client or *server */
766 /* return from in sa if not NULL */
767 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
769 unsigned char buf[4], *rad = NULL;
770 struct sockaddr_storage from;
771 socklen_t fromlen = sizeof(from);
773 struct list_node *node;
783 if (select(s + 1, &readfds, NULL, NULL, NULL) < 1)
785 cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
787 debug(DBG_WARN, "radudpget: recv failed");
791 debug(DBG_WARN, "radudpget: length too small");
796 p = find_conf(RAD_UDP, (struct sockaddr *)&from, client ? clconfs : srvconfs, NULL);
798 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
805 debug(DBG_WARN, "radudpget: length too small");
812 debug(DBG_ERR, "radudpget: malloc failed");
817 cnt = recv(s, rad, len, MSG_TRUNC);
818 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
821 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
825 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
828 node = list_first(p->clients);
829 *client = node ? (struct client *)node->data : addclient(p);
833 *server = p->servers;
841 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
842 int loc, i, l, n, r = 0;
845 STACK_OF(GENERAL_NAME) *alt;
848 debug(DBG_DBG, "subjectaltnameaddr");
850 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
854 ex = X509_get_ext(cert, loc);
855 alt = X509V3_EXT_d2i(ex);
859 n = sk_GENERAL_NAME_num(alt);
860 for (i = 0; i < n; i++) {
861 gn = sk_GENERAL_NAME_value(alt, i);
862 if (gn->type != GEN_IPADD)
865 v = (char *)ASN1_STRING_data(gn->d.ia5);
866 l = ASN1_STRING_length(gn->d.ia5);
867 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
868 && !memcmp(v, &addr, l)) {
873 GENERAL_NAMES_free(alt);
877 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
884 nm = X509_get_subject_name(cert);
887 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
890 e = X509_NAME_get_entry(nm, loc);
891 t = X509_NAME_ENTRY_get_data(e);
892 v = (char *) ASN1_STRING_data(t);
893 l = ASN1_STRING_length(t);
897 if (l == strlen(exact) && !strncasecmp(exact, v, l))
900 s = stringcopy((char *)v, l);
902 debug(DBG_ERR, "malloc failed");
905 if (regexec(regex, s, 0, NULL, 0)) {
916 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
917 int loc, i, l, n, r = 0;
920 STACK_OF(GENERAL_NAME) *alt;
923 debug(DBG_DBG, "subjectaltnameregexp");
925 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
929 ex = X509_get_ext(cert, loc);
930 alt = X509V3_EXT_d2i(ex);
934 n = sk_GENERAL_NAME_num(alt);
935 for (i = 0; i < n; i++) {
936 gn = sk_GENERAL_NAME_value(alt, i);
937 if (gn->type != type)
940 v = (char *)ASN1_STRING_data(gn->d.ia5);
941 l = ASN1_STRING_length(gn->d.ia5);
945 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
948 if (memcmp(v, exact, l))
951 s = stringcopy((char *)v, l);
953 debug(DBG_ERR, "malloc failed");
956 if (regexec(regex, s, 0, NULL, 0)) {
965 GENERAL_NAMES_free(alt);
969 X509 *verifytlscert(SSL *ssl) {
973 if (SSL_get_verify_result(ssl) != X509_V_OK) {
974 debug(DBG_ERR, "verifytlscert: basic validation failed");
975 while ((error = ERR_get_error()))
976 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
980 cert = SSL_get_peer_certificate(ssl);
982 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
986 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
988 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
989 struct in6_addr addr;
991 if (conf->certnamecheck && conf->prefixlen == 255) {
992 if (inet_pton(AF_INET, conf->host, &addr))
994 else if (inet_pton(AF_INET6, conf->host, &addr))
997 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
1000 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
1003 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
1005 if (!cnregexp(cert, conf->host, NULL)) {
1006 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
1009 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
1012 if (conf->certcnregex) {
1013 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
1014 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
1017 debug(DBG_DBG, "verifyconfcert: CN matching regex");
1019 if (conf->certuriregex) {
1020 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
1021 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
1024 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
1029 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
1033 unsigned long error;
1035 debug(DBG_DBG, "tlsconnect: called from %s", text);
1036 pthread_mutex_lock(&server->lock);
1037 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
1038 /* already reconnected, nothing to do */
1039 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
1040 pthread_mutex_unlock(&server->lock);
1045 gettimeofday(&now, NULL);
1046 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
1047 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
1048 debug(DBG_DBG, "tlsconnect: timeout");
1049 if (server->sock >= 0)
1050 close(server->sock);
1051 SSL_free(server->ssl);
1053 pthread_mutex_unlock(&server->lock);
1056 if (server->connectionok) {
1057 server->connectionok = 0;
1059 } else if (elapsed < 1)
1061 else if (elapsed < 60) {
1062 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
1064 } else if (elapsed < 100000) {
1065 debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
1068 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
1069 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
1070 if (server->sock >= 0)
1071 close(server->sock);
1072 if ((server->sock = connecttcp(server->conf->addrinfo, srcprotores[RAD_TLS])) < 0) {
1073 debug(DBG_ERR, "tlsconnect: connecttcp failed");
1077 SSL_free(server->ssl);
1078 server->ssl = SSL_new(server->conf->ssl_ctx);
1079 SSL_set_fd(server->ssl, server->sock);
1080 if (SSL_connect(server->ssl) <= 0) {
1081 while ((error = ERR_get_error()))
1082 debug(DBG_ERR, "tlsconnect: TLS: %s", ERR_error_string(error, NULL));
1085 cert = verifytlscert(server->ssl);
1088 if (verifyconfcert(cert, server->conf)) {
1094 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
1095 gettimeofday(&server->lastconnecttry, NULL);
1096 pthread_mutex_unlock(&server->lock);
1100 void *udpdtlsserverrd(void *arg) {
1101 int cnt, s = *(int *)arg;
1102 unsigned char buf[4];
1103 struct sockaddr_storage from;
1104 socklen_t fromlen = sizeof(from);
1105 struct clsrvconf *conf;
1106 struct list_node *node;
1107 struct client *client;
1109 pthread_t dtlsserverth;
1113 FD_SET(s, &readfds);
1114 if (select(s + 1, &readfds, NULL, NULL, NULL) < 1)
1116 cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
1118 debug(DBG_WARN, "udpdtlsserverrd: recv failed");
1121 conf = find_conf(RAD_DTLS, (struct sockaddr *)&from, clconfs, NULL);
1123 debug(DBG_WARN, "udpdtlsserverrd: got packet from wrong or unknown DTLS peer %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
1128 node = list_first(conf->clients);
1130 client = (struct client *)node->data;
1132 client = addclient(conf);
1138 memcpy(&client->addr, &from, fromlen);
1139 if (pthread_create(&dtlsserverth, NULL, dtlsservernew, (void *)client)) {
1140 debug(DBG_ERR, "udpdtlsserverrd: pthread_create failed");
1141 removeclient(client);
1145 pthread_detach(dtlsserverth);
1147 if (udp2bio(s, client->rbios, cnt))
1148 debug(DBG_DBG, "udpdtlsserverrd: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from, fromlen));
1152 void *dtlsserverwr(void *arg) {
1154 unsigned long error;
1155 struct client *client = (struct client *)arg;
1156 struct queue *replyq;
1157 struct reply *reply;
1159 debug(DBG_DBG, "dtlsserverwr: starting for %s", client->conf->host);
1160 replyq = client->replyq;
1162 pthread_mutex_lock(&replyq->mutex);
1163 while (!list_first(replyq->entries)) {
1165 debug(DBG_DBG, "dtlsserverwr: waiting for signal");
1166 pthread_cond_wait(&replyq->cond, &replyq->mutex);
1167 debug(DBG_DBG, "dtlsserverwr: got signal");
1170 /* ssl might have changed while waiting */
1171 pthread_mutex_unlock(&replyq->mutex);
1172 debug(DBG_DBG, "dtlsserverwr: exiting as requested");
1173 ERR_remove_state(0);
1177 reply = (struct reply *)list_shift(replyq->entries);
1178 pthread_mutex_unlock(&replyq->mutex);
1179 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
1181 debug(DBG_DBG, "dtlsserverwr: sent %d bytes, Radius packet of length %d",
1182 cnt, RADLEN(reply->buf));
1184 while ((error = ERR_get_error()))
1185 debug(DBG_ERR, "dtlsserverwr: SSL: %s", ERR_error_string(error, NULL));
1191 BIO *getrbio(SSL *ssl, struct queue *q, int timeout) {
1196 pthread_mutex_lock(&q->mutex);
1197 if (!(rbio = (BIO *)list_shift(q->entries))) {
1199 gettimeofday(&now, NULL);
1200 memset(&to, 0, sizeof(struct timespec));
1201 to.tv_sec = now.tv_sec + timeout;
1202 pthread_cond_timedwait(&q->cond, &q->mutex, &to);
1204 pthread_cond_wait(&q->cond, &q->mutex);
1205 rbio = (BIO *)list_shift(q->entries);
1207 pthread_mutex_unlock(&q->mutex);
1211 int dtlsread(SSL *ssl, struct queue *q, unsigned char *buf, int num) {
1214 for (len = 0; len < num; len += cnt) {
1215 cnt = SSL_read(ssl, buf + len, num - len);
1217 switch (cnt = SSL_get_error(ssl, cnt)) {
1218 case SSL_ERROR_WANT_READ:
1219 BIO_free(ssl->rbio);
1220 ssl->rbio = getrbio(ssl, q, 0);
1225 case SSL_ERROR_WANT_WRITE:
1228 case SSL_ERROR_ZERO_RETURN:
1229 /* remote end sent close_notify, send one back */
1239 unsigned char *raddtlsget(SSL *ssl, struct queue *rbios) {
1241 unsigned char buf[4], *rad;
1244 cnt = dtlsread(ssl, rbios, buf, 4);
1246 debug(DBG_DBG, "raddtlsget: connection lost");
1253 debug(DBG_ERR, "raddtlsget: malloc failed");
1256 memcpy(rad, buf, 4);
1258 cnt = dtlsread(ssl, rbios, rad + 4, len - 4);
1260 debug(DBG_DBG, "raddtlsget: connection lost");
1269 debug(DBG_WARN, "raddtlsget: packet smaller than minimum radius size");
1272 debug(DBG_DBG, "raddtlsget: got %d bytes", len);
1276 void dtlsserverrd(struct client *client) {
1278 pthread_t dtlsserverwrth;
1280 debug(DBG_DBG, "dtlsserverrd: starting for %s", client->conf->host);
1282 if (pthread_create(&dtlsserverwrth, NULL, dtlsserverwr, (void *)client)) {
1283 debug(DBG_ERR, "dtlsserverrd: pthread_create failed");
1288 memset(&rq, 0, sizeof(struct request));
1289 rq.buf = raddtlsget(client->ssl, client->rbios);
1291 debug(DBG_ERR, "dtlsserverrd: connection from %s lost", client->conf->host);
1294 debug(DBG_DBG, "dtlsserverrd: got Radius message from %s", client->conf->host);
1297 debug(DBG_ERR, "dtlsserverrd: message authentication/validation failed, closing connection from %s", client->conf->host);
1302 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
1305 pthread_mutex_lock(&client->replyq->mutex);
1306 pthread_cond_signal(&client->replyq->cond);
1307 pthread_mutex_unlock(&client->replyq->mutex);
1308 debug(DBG_DBG, "dtlsserverrd: waiting for writer to end");
1309 pthread_join(dtlsserverwrth, NULL);
1310 removeclientrqs(client);
1311 debug(DBG_DBG, "dtlsserverrd: reader for %s exiting", client->conf->host);
1314 /* accept if acc == 1, else connect */
1315 SSL *dtlsacccon(uint8_t acc, SSL_CTX *ctx, int s, struct sockaddr *addr, struct queue *rbios) {
1318 unsigned long error;
1319 BIO *mem0bio, *wbio;
1325 mem0bio = BIO_new(BIO_s_mem());
1326 BIO_set_mem_eof_return(mem0bio, -1);
1327 wbio = BIO_new_dgram(s, BIO_NOCLOSE);
1328 BIO_dgram_set_peer(wbio, addr);
1329 SSL_set_bio(ssl, mem0bio, wbio);
1331 for (i = 0; i < 5; i++) {
1332 res = acc ? SSL_accept(ssl) : SSL_connect(ssl);
1337 if (SSL_get_error(ssl, res) == SSL_ERROR_WANT_READ) {
1338 BIO_free(ssl->rbio);
1339 ssl->rbio = getrbio(ssl, rbios, 5);
1343 while ((error = ERR_get_error()))
1344 debug(DBG_ERR, "dtls%st: DTLS: %s", acc ? "accep" : "connec", ERR_error_string(error, NULL));
1351 void *dtlsservernew(void *arg) {
1352 struct client *client = (struct client *)arg;
1355 client->ssl = dtlsacccon(1, client->conf->ssl_ctx, client->sock, (struct sockaddr *)&client->addr, client->rbios);
1358 cert = verifytlscert(client->ssl);
1361 if (verifyconfcert(cert, client->conf)) {
1363 dtlsserverrd(client);
1364 removeclient(client);
1366 debug(DBG_WARN, "dtlsservernew: ignoring request, certificate validation failed");
1371 SSL_free(client->ssl);
1372 ERR_remove_state(0);
1376 int dtlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
1381 debug(DBG_DBG, "dtlsconnect: called from %s", text);
1382 pthread_mutex_lock(&server->lock);
1383 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
1384 /* already reconnected, nothing to do */
1385 debug(DBG_DBG, "dtlsconnect(%s): seems already reconnected", text);
1386 pthread_mutex_unlock(&server->lock);
1391 gettimeofday(&now, NULL);
1392 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
1394 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
1395 debug(DBG_DBG, "dtlsconnect: timeout");
1396 SSL_free(server->ssl);
1398 pthread_mutex_unlock(&server->lock);
1402 if (server->connectionok) {
1403 server->connectionok = 0;
1405 } else if (elapsed < 1)
1407 else if (elapsed < 60) {
1408 debug(DBG_INFO, "dtlsconnect: sleeping %lds", elapsed);
1410 } else if (elapsed < 100000) {
1411 debug(DBG_INFO, "dtlsconnect: sleeping %ds", 60);
1414 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
1415 debug(DBG_WARN, "dtlsconnect: trying to open DTLS connection to %s port %s", server->conf->host, server->conf->port);
1417 SSL_free(server->ssl);
1418 server->ssl = dtlsacccon(0, server->conf->ssl_ctx, server->sock, server->conf->addrinfo->ai_addr, server->rbios);
1421 debug(DBG_DBG, "dtlsconnect: DTLS: ok");
1423 cert = verifytlscert(server->ssl);
1427 if (verifyconfcert(cert, server->conf))
1432 debug(DBG_WARN, "dtlsconnect: DTLS connection to %s port %s up", server->conf->host, server->conf->port);
1433 gettimeofday(&server->lastconnecttry, NULL);
1434 pthread_mutex_unlock(&server->lock);
1438 int tcpconnect(struct server *server, struct timeval *when, int timeout, char *text) {
1442 debug(DBG_DBG, "tcpconnect: called from %s", text);
1443 pthread_mutex_lock(&server->lock);
1444 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
1445 /* already reconnected, nothing to do */
1446 debug(DBG_DBG, "tcpconnect(%s): seems already reconnected", text);
1447 pthread_mutex_unlock(&server->lock);
1452 gettimeofday(&now, NULL);
1453 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
1454 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
1455 debug(DBG_DBG, "tcpconnect: timeout");
1456 if (server->sock >= 0)
1457 close(server->sock);
1458 pthread_mutex_unlock(&server->lock);
1461 if (server->connectionok) {
1462 server->connectionok = 0;
1464 } else if (elapsed < 1)
1466 else if (elapsed < 60) {
1467 debug(DBG_INFO, "tcpconnect: sleeping %lds", elapsed);
1469 } else if (elapsed < 100000) {
1470 debug(DBG_INFO, "tcpconnect: sleeping %ds", 60);
1473 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
1474 debug(DBG_WARN, "tcpconnect: trying to open TCP connection to %s port %s", server->conf->host, server->conf->port);
1475 if (server->sock >= 0)
1476 close(server->sock);
1477 if ((server->sock = connecttcp(server->conf->addrinfo, srcprotores[RAD_TCP])) >= 0)
1479 debug(DBG_ERR, "tcpconnect: connecttcp failed");
1481 debug(DBG_WARN, "tcpconnect: TCP connection to %s port %s up", server->conf->host, server->conf->port);
1482 gettimeofday(&server->lastconnecttry, NULL);
1483 pthread_mutex_unlock(&server->lock);
1487 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
1488 /* returns 0 on timeout, -1 on error and num if ok */
1489 int sslreadtimeout(SSL *ssl, unsigned char *buf, int num, int timeout) {
1490 int s, ndesc, cnt, len;
1491 fd_set readfds, writefds;
1492 struct timeval timer;
1494 s = SSL_get_fd(ssl);
1497 /* make socket non-blocking? */
1498 for (len = 0; len < num; len += cnt) {
1500 FD_SET(s, &readfds);
1503 timer.tv_sec = timeout;
1506 ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
1510 cnt = SSL_read(ssl, buf + len, num - len);
1512 switch (SSL_get_error(ssl, cnt)) {
1513 case SSL_ERROR_WANT_READ:
1514 case SSL_ERROR_WANT_WRITE:
1517 case SSL_ERROR_ZERO_RETURN:
1518 /* remote end sent close_notify, send one back */
1528 /* timeout in seconds, 0 means no timeout (blocking) */
1529 unsigned char *radtlsget(SSL *ssl, int timeout) {
1531 unsigned char buf[4], *rad;
1534 cnt = sslreadtimeout(ssl, buf, 4, timeout);
1536 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1543 debug(DBG_ERR, "radtlsget: malloc failed");
1546 memcpy(rad, buf, 4);
1548 cnt = sslreadtimeout(ssl, rad + 4, len - 4, timeout);
1550 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1559 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
1562 debug(DBG_DBG, "radtlsget: got %d bytes", len);
1566 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
1567 /* returns 0 on timeout, -1 on error and num if ok */
1568 int tcpreadtimeout(int s, unsigned char *buf, int num, int timeout) {
1569 int ndesc, cnt, len;
1570 fd_set readfds, writefds;
1571 struct timeval timer;
1575 /* make socket non-blocking? */
1576 for (len = 0; len < num; len += cnt) {
1578 FD_SET(s, &readfds);
1581 timer.tv_sec = timeout;
1584 ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
1588 cnt = read(s, buf + len, num - len);
1595 /* timeout in seconds, 0 means no timeout (blocking) */
1596 unsigned char *radtcpget(int s, int timeout) {
1598 unsigned char buf[4], *rad;
1601 cnt = tcpreadtimeout(s, buf, 4, timeout);
1603 debug(DBG_DBG, cnt ? "radtcpget: connection lost" : "radtcpget: timeout");
1610 debug(DBG_ERR, "radtcpget: malloc failed");
1613 memcpy(rad, buf, 4);
1615 cnt = tcpreadtimeout(s, rad + 4, len - 4, timeout);
1617 debug(DBG_DBG, cnt ? "radtcpget: connection lost" : "radtcpget: timeout");
1626 debug(DBG_WARN, "radtcpget: packet smaller than minimum radius size");
1629 debug(DBG_DBG, "radtcpget: got %d bytes", len);
1633 int clientradputudp(struct server *server, unsigned char *rad) {
1635 struct sockaddr_storage sa;
1636 struct sockaddr *sap;
1637 struct clsrvconf *conf = server->conf;
1638 in_port_t *port = NULL;
1642 if (*rad == RAD_Accounting_Request) {
1643 sap = (struct sockaddr *)&sa;
1644 memcpy(sap, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen);
1646 sap = conf->addrinfo->ai_addr;
1648 switch (sap->sa_family) {
1650 port = &((struct sockaddr_in *)sap)->sin_port;
1653 port = &((struct sockaddr_in6 *)sap)->sin6_port;
1659 if (*rad == RAD_Accounting_Request)
1660 *port = htons(ntohs(*port) + 1);
1662 if (sendto(server->sock, rad, len, 0, sap, conf->addrinfo->ai_addrlen) >= 0) {
1663 debug(DBG_DBG, "clienradputudp: sent UDP of length %d to %s port %d", len, conf->host, ntohs(*port));
1667 debug(DBG_WARN, "clientradputudp: send failed");
1671 int clientradputtls(struct server *server, unsigned char *rad) {
1674 unsigned long error;
1675 struct timeval lastconnecttry;
1676 struct clsrvconf *conf = server->conf;
1679 lastconnecttry = server->lastconnecttry;
1680 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
1681 while ((error = ERR_get_error()))
1682 debug(DBG_ERR, "clientradputtls: TLS: %s", ERR_error_string(error, NULL));
1683 if (server->dynamiclookuparg)
1685 tlsconnect(server, &lastconnecttry, 0, "clientradputtls");
1686 lastconnecttry = server->lastconnecttry;
1689 server->connectionok = 1;
1690 debug(DBG_DBG, "clientradputtls: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
1694 int clientradputdtls(struct server *server, unsigned char *rad) {
1697 unsigned long error;
1698 struct clsrvconf *conf = server->conf;
1701 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
1702 while ((error = ERR_get_error()))
1703 debug(DBG_ERR, "clientradputdtls: DTLS: %s", ERR_error_string(error, NULL));
1705 debug(DBG_DBG, "clientradputdtls: Sent %d bytes, Radius packet of length %d to DTLS peer %s", cnt, len, conf->host);
1709 int clientradputtcp(struct server *server, unsigned char *rad) {
1712 struct timeval lastconnecttry;
1713 struct clsrvconf *conf = server->conf;
1716 lastconnecttry = server->lastconnecttry;
1717 while ((cnt = write(server->sock, rad, len)) <= 0) {
1718 debug(DBG_ERR, "clientradputtcp: write error");
1719 tcpconnect(server, &lastconnecttry, 0, "clientradputtcp");
1720 lastconnecttry = server->lastconnecttry;
1723 server->connectionok = 1;
1724 debug(DBG_DBG, "clientradputtcp: Sent %d bytes, Radius packet of length %d to TCP peer %s", cnt, len, conf->host);
1728 int radsign(unsigned char *rad, unsigned char *sec) {
1729 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1730 static unsigned char first = 1;
1731 static EVP_MD_CTX mdctx;
1732 unsigned int md_len;
1735 pthread_mutex_lock(&lock);
1737 EVP_MD_CTX_init(&mdctx);
1741 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1742 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
1743 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1744 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
1746 pthread_mutex_unlock(&lock);
1750 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
1751 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1752 static unsigned char first = 1;
1753 static EVP_MD_CTX mdctx;
1754 unsigned char hash[EVP_MAX_MD_SIZE];
1758 pthread_mutex_lock(&lock);
1760 EVP_MD_CTX_init(&mdctx);
1766 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1767 EVP_DigestUpdate(&mdctx, rad, 4) &&
1768 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
1769 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
1770 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1771 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
1773 !memcmp(hash, rad + 4, 16));
1774 pthread_mutex_unlock(&lock);
1778 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
1779 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1780 static unsigned char first = 1;
1781 static HMAC_CTX hmacctx;
1782 unsigned int md_len;
1783 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
1785 pthread_mutex_lock(&lock);
1787 HMAC_CTX_init(&hmacctx);
1791 memcpy(auth, authattr, 16);
1792 memset(authattr, 0, 16);
1794 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1795 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1796 HMAC_Final(&hmacctx, hash, &md_len);
1797 memcpy(authattr, auth, 16);
1799 debug(DBG_WARN, "message auth computation failed");
1800 pthread_mutex_unlock(&lock);
1804 if (memcmp(auth, hash, 16)) {
1805 debug(DBG_WARN, "message authenticator, wrong value");
1806 pthread_mutex_unlock(&lock);
1810 pthread_mutex_unlock(&lock);
1814 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
1815 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1816 static unsigned char first = 1;
1817 static HMAC_CTX hmacctx;
1818 unsigned int md_len;
1823 pthread_mutex_lock(&lock);
1825 HMAC_CTX_init(&hmacctx);
1829 memset(authattrval, 0, 16);
1831 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1832 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1833 HMAC_Final(&hmacctx, authattrval, &md_len);
1835 debug(DBG_WARN, "message auth computation failed");
1836 pthread_mutex_unlock(&lock);
1840 pthread_mutex_unlock(&lock);
1844 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
1845 while (length > 1) {
1846 if (ATTRTYPE(attrs) == type)
1848 length -= ATTRLEN(attrs);
1849 attrs += ATTRLEN(attrs);
1854 void freerqdata(struct request *rq) {
1855 if (rq->origusername)
1856 free(rq->origusername);
1861 void sendrq(struct server *to, struct request *rq) {
1865 pthread_mutex_lock(&to->newrq_mutex);
1866 /* might simplify if only try nextid, might be ok */
1867 for (i = to->nextid; i < MAX_REQUESTS; i++)
1868 if (!to->requests[i].buf)
1870 if (i == MAX_REQUESTS) {
1871 for (i = 0; i < to->nextid; i++)
1872 if (!to->requests[i].buf)
1874 if (i == to->nextid) {
1875 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
1881 rq->buf[1] = (char)i;
1883 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1884 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1889 if (*rq->buf == RAD_Accounting_Request) {
1890 if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
1891 debug(DBG_WARN, "sendrq: failed to sign Accounting-Request message");
1897 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1898 to->requests[i] = *rq;
1903 debug(DBG_DBG, "sendrq: signalling client writer");
1904 pthread_cond_signal(&to->newrq_cond);
1907 pthread_mutex_unlock(&to->newrq_mutex);
1910 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa, int toudpsock) {
1911 struct reply *reply;
1914 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1916 debug(DBG_WARN, "sendreply: failed to sign message");
1920 reply = malloc(sizeof(struct reply));
1923 debug(DBG_ERR, "sendreply: malloc failed");
1926 memset(reply, 0, sizeof(struct reply));
1929 reply->tosa = *tosa;
1930 reply->toudpsock = toudpsock;
1932 pthread_mutex_lock(&to->replyq->mutex);
1934 first = list_first(to->replyq->entries) == NULL;
1936 if (!list_push(to->replyq->entries, reply)) {
1937 pthread_mutex_unlock(&to->replyq->mutex);
1940 debug(DBG_ERR, "sendreply: malloc failed");
1945 debug(DBG_DBG, "signalling server writer");
1946 pthread_cond_signal(&to->replyq->cond);
1948 pthread_mutex_unlock(&to->replyq->mutex);
1951 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1952 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1953 static unsigned char first = 1;
1954 static EVP_MD_CTX mdctx;
1955 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1956 unsigned int md_len;
1957 uint8_t i, offset = 0, out[128];
1959 pthread_mutex_lock(&lock);
1961 EVP_MD_CTX_init(&mdctx);
1967 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1968 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1969 !EVP_DigestUpdate(&mdctx, input, 16) ||
1970 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1972 pthread_mutex_unlock(&lock);
1975 for (i = 0; i < 16; i++)
1976 out[offset + i] = hash[i] ^ in[offset + i];
1977 input = out + offset - 16;
1982 memcpy(in, out, len);
1983 pthread_mutex_unlock(&lock);
1987 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1988 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1989 static unsigned char first = 1;
1990 static EVP_MD_CTX mdctx;
1991 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1992 unsigned int md_len;
1993 uint8_t i, offset = 0, out[128];
1995 pthread_mutex_lock(&lock);
1997 EVP_MD_CTX_init(&mdctx);
2003 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
2004 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
2005 !EVP_DigestUpdate(&mdctx, input, 16) ||
2006 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
2008 pthread_mutex_unlock(&lock);
2011 for (i = 0; i < 16; i++)
2012 out[offset + i] = hash[i] ^ in[offset + i];
2013 input = in + offset;
2018 memcpy(in, out, len);
2019 pthread_mutex_unlock(&lock);
2023 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
2024 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
2025 static unsigned char first = 1;
2026 static EVP_MD_CTX mdctx;
2027 unsigned char hash[EVP_MAX_MD_SIZE];
2028 unsigned int md_len;
2031 pthread_mutex_lock(&lock);
2033 EVP_MD_CTX_init(&mdctx);
2038 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
2039 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
2040 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
2043 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
2044 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
2045 !EVP_DigestUpdate(&mdctx, auth, 16) ||
2046 !EVP_DigestUpdate(&mdctx, salt, 2) ||
2047 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
2048 pthread_mutex_unlock(&lock);
2053 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
2056 for (i = 0; i < 16; i++)
2059 for (offset = 16; offset < len; offset += 16) {
2061 printf("text + offset - 16 c(%d): ", offset / 16);
2062 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
2064 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
2065 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
2066 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
2067 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
2069 pthread_mutex_unlock(&lock);
2073 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
2076 for (i = 0; i < 16; i++)
2077 text[offset + i] ^= hash[i];
2081 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
2084 pthread_mutex_unlock(&lock);
2088 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
2089 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
2090 static unsigned char first = 1;
2091 static EVP_MD_CTX mdctx;
2092 unsigned char hash[EVP_MAX_MD_SIZE];
2093 unsigned int md_len;
2097 pthread_mutex_lock(&lock);
2099 EVP_MD_CTX_init(&mdctx);
2104 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
2105 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
2106 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
2109 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
2110 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
2111 !EVP_DigestUpdate(&mdctx, auth, 16) ||
2112 !EVP_DigestUpdate(&mdctx, salt, 2) ||
2113 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
2114 pthread_mutex_unlock(&lock);
2119 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
2122 for (i = 0; i < 16; i++)
2123 plain[i] = text[i] ^ hash[i];
2125 for (offset = 16; offset < len; offset += 16) {
2127 printf("text + offset - 16 c(%d): ", offset / 16);
2128 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
2130 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
2131 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
2132 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
2133 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
2135 pthread_mutex_unlock(&lock);
2139 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
2142 for (i = 0; i < 16; i++)
2143 plain[offset + i] = text[offset + i] ^ hash[i];
2146 memcpy(text, plain, len);
2148 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
2151 pthread_mutex_unlock(&lock);
2155 struct realm *id2realm(struct list *realmlist, char *id) {
2156 struct list_node *entry;
2157 struct realm *realm, *subrealm = NULL;
2159 /* need to do locking for subrealms and check subrealm timers */
2160 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
2161 realm = (struct realm *)entry->data;
2162 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
2163 pthread_mutex_lock(&realm->subrealms_mutex);
2164 if (realm->subrealms)
2165 subrealm = id2realm(realm->subrealms, id);
2166 pthread_mutex_unlock(&realm->subrealms_mutex);
2167 return subrealm ? subrealm : realm;
2173 /* helper function, only used by removeserversubrealms() */
2174 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
2175 struct list_node *entry;
2176 struct realm *realm;
2178 for (entry = list_first(realmlist); entry;) {
2179 realm = (struct realm *)entry->data;
2180 entry = list_next(entry);
2181 if (realm->srvconfs) {
2182 list_removedata(realm->srvconfs, srv);
2183 if (!list_first(realm->srvconfs)) {
2184 list_destroy(realm->srvconfs);
2185 realm->srvconfs = NULL;
2188 if (realm->accsrvconfs) {
2189 list_removedata(realm->accsrvconfs, srv);
2190 if (!list_first(realm->accsrvconfs)) {
2191 list_destroy(realm->accsrvconfs);
2192 realm->accsrvconfs = NULL;
2196 /* remove subrealm if no servers */
2197 if (!realm->srvconfs && !realm->accsrvconfs) {
2198 list_removedata(realmlist, realm);
2204 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
2205 struct list_node *entry;
2206 struct realm *realm;
2208 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
2209 realm = (struct realm *)entry->data;
2210 pthread_mutex_lock(&realm->subrealms_mutex);
2211 if (realm->subrealms) {
2212 _internal_removeserversubrealms(realm->subrealms, srv);
2213 if (!list_first(realm->subrealms)) {
2214 list_destroy(realm->subrealms);
2215 realm->subrealms = NULL;
2218 pthread_mutex_unlock(&realm->subrealms_mutex);
2222 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
2223 struct request *rq = to->requests, *end;
2225 pthread_mutex_lock(&to->newrq_mutex);
2226 for (end = rq + MAX_REQUESTS; rq < end; rq++)
2227 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
2229 pthread_mutex_unlock(&to->newrq_mutex);
2234 int attrvalidate(unsigned char *attrs, int length) {
2235 while (length > 1) {
2236 if (ATTRLEN(attrs) < 2) {
2237 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
2240 length -= ATTRLEN(attrs);
2242 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
2245 attrs += ATTRLEN(attrs);
2248 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
2252 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
2253 if (len < 16 || len > 128 || len % 16) {
2254 debug(DBG_WARN, "pwdrecrypt: invalid password length");
2258 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
2259 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
2263 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
2265 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
2266 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
2272 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
2275 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
2276 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
2279 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
2280 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
2286 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
2287 char *oldsecret, char *newsecret) {
2288 unsigned char *attr;
2290 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
2291 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
2292 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
2298 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
2302 for (; attrs[0]; attrs += 2)
2303 if (attrs[0] == vendor && attrs[1] == subattr)
2308 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
2309 uint8_t alen, sublen, rmlen = 0;
2310 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
2313 if (!removevendorattrs)
2316 while (*removevendorattrs && *removevendorattrs != vendor)
2317 removevendorattrs += 2;
2318 if (!*removevendorattrs)
2321 alen = ATTRLEN(attrs);
2323 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
2324 /* remove entire vendor attribute */
2325 memmove(attrs, attrs + alen, length - alen);
2330 subattrs = ATTRVAL(attrs) + 4;
2332 if (!attrvalidate(subattrs, sublen)) {
2333 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
2338 while (sublen > 1) {
2339 alen = ATTRLEN(subattrs);
2342 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
2343 memmove(subattrs, subattrs + alen, length);
2349 ATTRLEN(attrs) -= rmlen;
2353 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
2354 uint8_t *attrs, alen;
2355 uint16_t len, rmlen = 0;
2357 if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
2360 len = RADLEN(buf) - 20;
2363 alen = ATTRLEN(attrs);
2365 if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
2366 memmove(attrs, attrs + alen, len);
2368 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
2369 rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
2374 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
2377 /* returns a pointer to the resized attribute value */
2378 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
2379 uint8_t *attrs, *attr, vallen;
2383 len = RADLEN(*buf) - 20;
2386 attr = attrget(attrs, len, type);
2390 vallen = ATTRVALLEN(attr);
2391 if (vallen == newvallen)
2394 len += newvallen - vallen;
2395 if (newvallen > vallen) {
2396 new = realloc(*buf, len + 20);
2398 debug(DBG_ERR, "resizeattr: malloc failed");
2407 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
2408 attr[1] = newvallen + 2;
2409 ((uint16_t *)*buf)[1] = htons(len + 20);
2413 int rewriteusername(struct request *rq, char *in) {
2414 size_t nmatch = 10, reslen = 0, start = 0;
2415 regmatch_t pmatch[10], *pfield;
2417 unsigned char *result;
2418 char *out = rq->from->conf->rewriteattrreplacement;
2420 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
2421 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
2425 rq->origusername = stringcopy(in, 0);
2426 if (!rq->origusername)
2429 for (i = start; out[i]; i++) {
2430 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
2431 pfield = &pmatch[out[i + 1] - '0'];
2432 if (pfield->rm_so >= 0) {
2433 reslen += i - start + pfield->rm_eo - pfield->rm_so;
2439 reslen += i - start;
2441 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
2447 for (i = start; out[i]; i++) {
2448 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
2449 pfield = &pmatch[out[i + 1] - '0'];
2450 if (pfield->rm_so >= 0) {
2451 memcpy(result + reslen, out + start, i - start);
2452 reslen += i - start;
2453 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
2454 reslen += pfield->rm_eo - pfield->rm_so;
2461 memcpy(result + reslen, out + start, i - start);
2462 reslen += i - start;
2463 memcpy(in, result, reslen);
2468 const char *radmsgtype2string(uint8_t code) {
2469 static const char *rad_msg_names[] = {
2470 "", "Access-Request", "Access-Accept", "Access-Reject",
2471 "Accounting-Request", "Accounting-Response", "", "",
2472 "", "", "", "Access-Challenge",
2473 "Status-Server", "Status-Client"
2475 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
2478 void char2hex(char *h, unsigned char c) {
2479 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
2480 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
2481 h[0] = hexdigits[c / 16];
2482 h[1] = hexdigits[c % 16];
2486 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
2490 if (!attr || len == 1) {
2495 l = ATTRVALLEN(attr);
2496 s = (char *)ATTRVAL(attr);
2499 for (i = 0; i < l; i++) {
2500 if (s[i] > 31 && s[i] < 127) {
2502 if (d - ascii == len - 1)
2505 if (d - ascii > len - 4)
2510 if (d - ascii == len - 1)
2518 void acclog(unsigned char *attrs, int length, char *host) {
2519 unsigned char *attr;
2522 attr = attrget(attrs, length, RAD_Attr_User_Name);
2524 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
2527 radattr2ascii(username, sizeof(username), attr);
2528 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
2531 void respondaccounting(struct request *rq) {
2532 unsigned char *resp;
2536 debug(DBG_ERR, "respondaccounting: malloc failed");
2539 memcpy(resp, rq->buf, 20);
2540 resp[0] = RAD_Accounting_Response;
2543 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
2544 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2547 void respondstatusserver(struct request *rq) {
2548 unsigned char *resp;
2552 debug(DBG_ERR, "respondstatusserver: malloc failed");
2555 memcpy(resp, rq->buf, 20);
2556 resp[0] = RAD_Access_Accept;
2559 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
2560 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2563 void respondreject(struct request *rq, char *message) {
2564 unsigned char *resp;
2567 if (message && *message)
2568 len += 2 + strlen(message);
2572 debug(DBG_ERR, "respondreject: malloc failed");
2575 memcpy(resp, rq->buf, 20);
2576 resp[0] = RAD_Access_Reject;
2577 *(uint16_t *)(resp + 2) = htons(len);
2578 if (message && *message) {
2579 resp[20] = RAD_Attr_Reply_Message;
2580 resp[21] = len - 20;
2581 memcpy(resp + 22, message, len - 22);
2583 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2586 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
2587 struct list_node *entry;
2588 struct clsrvconf *server, *best = NULL, *first = NULL;
2590 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2591 server = (struct clsrvconf *)entry->data;
2592 if (!server->servers)
2596 if (!server->servers->connectionok)
2598 if (!server->servers->lostrqs)
2604 if (server->servers->lostrqs < best->servers->lostrqs)
2607 return best ? best : first;
2610 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
2611 struct clsrvconf *srvconf;
2613 *realm = id2realm(realms, id);
2616 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
2617 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
2620 if (!acc && !srvconf->servers)
2621 adddynamicrealmserver(*realm, srvconf, id);
2622 return srvconf->servers;
2625 /* returns 0 if validation/authentication fails, else 1 */
2626 int radsrv(struct request *rq) {
2627 uint8_t code, id, *auth, *attrs, *attr;
2629 struct server *to = NULL;
2630 char username[254], userascii[760];
2631 unsigned char newauth[16];
2632 struct realm *realm = NULL;
2634 code = *(uint8_t *)rq->buf;
2635 id = *(uint8_t *)(rq->buf + 1);
2636 len = RADLEN(rq->buf);
2637 auth = (uint8_t *)(rq->buf + 4);
2639 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
2641 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
2642 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
2647 attrs = rq->buf + 20;
2649 if (!attrvalidate(attrs, len)) {
2650 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
2654 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2655 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
2656 debug(DBG_WARN, "radsrv: message authentication failed");
2660 if (code == RAD_Status_Server) {
2661 respondstatusserver(rq);
2665 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
2667 if (code == RAD_Accounting_Request) {
2668 memset(newauth, 0, 16);
2669 if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
2670 debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
2675 if (rq->from->conf->rewrite) {
2676 dorewrite(rq->buf, rq->from->conf->rewrite);
2677 len = RADLEN(rq->buf) - 20;
2680 attr = attrget(attrs, len, RAD_Attr_User_Name);
2682 if (code == RAD_Accounting_Request) {
2683 acclog(attrs, len, rq->from->conf->host);
2684 respondaccounting(rq);
2686 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
2689 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
2690 username[ATTRVALLEN(attr)] = '\0';
2691 radattr2ascii(userascii, sizeof(userascii), attr);
2693 if (rq->from->conf->rewriteattrregex) {
2694 if (!rewriteusername(rq, username)) {
2695 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
2698 len = RADLEN(rq->buf) - 20;
2699 auth = (uint8_t *)(rq->buf + 4);
2700 attrs = rq->buf + 20;
2703 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
2705 to = findserver(&realm, username, code == RAD_Accounting_Request);
2707 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
2711 if (realm->message && code == RAD_Access_Request) {
2712 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
2713 respondreject(rq, realm->message);
2714 } else if (realm->accresp && code == RAD_Accounting_Request) {
2715 acclog(attrs, len, rq->from->conf->host);
2716 respondaccounting(rq);
2721 if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
2722 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
2723 rq->from->conf->name, to->conf->name);
2727 if (rqinqueue(to, rq->from, id, code)) {
2728 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
2729 radmsgtype2string(code), rq->from->conf->host, id);
2733 if (code != RAD_Accounting_Request) {
2734 if (!RAND_bytes(newauth, 16)) {
2735 debug(DBG_WARN, "radsrv: failed to generate random auth");
2741 printfchars(NULL, "auth", "%02x ", auth, 16);
2744 attr = attrget(attrs, len, RAD_Attr_User_Password);
2746 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
2747 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2751 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
2753 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
2754 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2759 memcpy(rq->origauth, auth, 16);
2760 memcpy(auth, newauth, 16);
2773 int replyh(struct server *server, unsigned char *buf) {
2774 struct client *from;
2777 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
2778 struct sockaddr_storage fromsa;
2779 char tmp[760], stationid[760];
2781 server->connectionok = 1;
2782 server->lostrqs = 0;
2784 i = buf[1]; /* i is the id */
2786 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
2787 && *buf != RAD_Accounting_Response) {
2788 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
2791 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
2793 rq = server->requests + i;
2795 pthread_mutex_lock(&server->newrq_mutex);
2796 if (!rq->buf || !rq->tries) {
2797 pthread_mutex_unlock(&server->newrq_mutex);
2798 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
2803 pthread_mutex_unlock(&server->newrq_mutex);
2804 debug(DBG_INFO, "replyh: already received, ignoring reply");
2808 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
2809 pthread_mutex_unlock(&server->newrq_mutex);
2810 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
2814 len = RADLEN(buf) - 20;
2817 if (!attrvalidate(attrs, len)) {
2818 pthread_mutex_unlock(&server->newrq_mutex);
2819 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
2823 /* Message Authenticator */
2824 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2826 if (ATTRVALLEN(messageauth) != 16) {
2827 pthread_mutex_unlock(&server->newrq_mutex);
2828 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
2831 memcpy(tmp, buf + 4, 16);
2832 memcpy(buf + 4, rq->buf + 4, 16);
2833 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
2834 pthread_mutex_unlock(&server->newrq_mutex);
2835 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
2838 memcpy(buf + 4, tmp, 16);
2839 debug(DBG_DBG, "replyh: message auth ok");
2842 gettimeofday(&server->lastrcv, NULL);
2844 if (*rq->buf == RAD_Status_Server) {
2846 pthread_mutex_unlock(&server->newrq_mutex);
2847 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2851 gettimeofday(&server->lastreply, NULL);
2855 pthread_mutex_unlock(&server->newrq_mutex);
2856 debug(DBG_INFO, "replyh: client gone, ignoring reply");
2860 if (server->conf->rewrite) {
2861 dorewrite(buf, server->conf->rewrite);
2862 len = RADLEN(buf) - 20;
2866 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2867 if (ATTRVALLEN(attr) <= 4)
2870 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
2873 sublen = ATTRVALLEN(attr) - 4;
2874 subattrs = ATTRVAL(attr) + 4;
2875 if (!attrvalidate(subattrs, sublen) ||
2876 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2877 rq, server->conf->secret, from->conf->secret) ||
2878 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2879 rq, server->conf->secret, from->conf->secret))
2883 pthread_mutex_unlock(&server->newrq_mutex);
2884 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2888 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2889 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2891 radattr2ascii(tmp, sizeof(tmp), attr);
2892 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2894 radattr2ascii(stationid, sizeof(stationid), attr);
2895 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2896 radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2898 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2902 buf[1] = (char)rq->origid;
2903 memcpy(buf + 4, rq->origauth, 16);
2905 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2908 if (rq->origusername) {
2909 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2911 pthread_mutex_unlock(&server->newrq_mutex);
2912 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2915 memcpy(username, rq->origusername, strlen(rq->origusername));
2916 len = RADLEN(buf) - 20;
2919 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2923 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2924 pthread_mutex_unlock(&server->newrq_mutex);
2925 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2928 debug(DBG_DBG, "replyh: computed messageauthattr");
2931 fromsa = rq->fromsa; /* only needed for UDP */
2932 /* once we set received = 1, rq may be reused */
2935 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2936 sendreply(from, buf, &fromsa, rq->fromudpsock);
2937 pthread_mutex_unlock(&server->newrq_mutex);
2941 void *udpclientrd(void *arg) {
2942 struct server *server;
2944 int *s = (int *)arg;
2948 buf = radudpget(*s, NULL, &server, NULL);
2949 if (!replyh(server, buf))
2954 void *tlsclientrd(void *arg) {
2955 struct server *server = (struct server *)arg;
2957 struct timeval now, lastconnecttry;
2960 /* yes, lastconnecttry is really necessary */
2961 lastconnecttry = server->lastconnecttry;
2962 buf = radtlsget(server->ssl, server->dynamiclookuparg ? IDLE_TIMEOUT : 0);
2964 if (server->dynamiclookuparg)
2966 tlsconnect(server, &lastconnecttry, 0, "tlsclientrd");
2970 if (!replyh(server, buf))
2972 if (server->dynamiclookuparg) {
2973 gettimeofday(&now, NULL);
2974 if (now.tv_sec - server->lastreply.tv_sec > IDLE_TIMEOUT) {
2975 debug(DBG_INFO, "tlsclientrd: idle timeout for %s", server->conf->name);
2980 ERR_remove_state(0);
2981 server->clientrdgone = 1;
2985 void *udpdtlsclientrd(void *arg) {
2986 int cnt, s = *(int *)arg;
2987 unsigned char buf[4];
2988 struct sockaddr_storage from;
2989 socklen_t fromlen = sizeof(from);
2990 struct clsrvconf *conf;
2995 FD_SET(s, &readfds);
2996 if (select(s + 1, &readfds, NULL, NULL, NULL) < 1)
2998 cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
3000 debug(DBG_WARN, "udpdtlsclientrd: recv failed");
3004 conf = find_conf(RAD_DTLS, (struct sockaddr *)&from, srvconfs, NULL);
3006 debug(DBG_WARN, "udpdtlsclientrd: got packet from wrong or unknown DTLS peer %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
3010 if (udp2bio(s, conf->servers->rbios, cnt))
3011 debug(DBG_DBG, "radudpget: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from, fromlen));
3015 void *dtlsclientrd(void *arg) {
3016 struct server *server = (struct server *)arg;
3018 struct timeval lastconnecttry;
3021 /* yes, lastconnecttry is really necessary */
3022 lastconnecttry = server->lastconnecttry;
3023 buf = raddtlsget(server->ssl, server->rbios);
3025 dtlsconnect(server, &lastconnecttry, 0, "dtlsclientrd");
3029 if (!replyh(server, buf))
3034 void *tcpclientrd(void *arg) {
3035 struct server *server = (struct server *)arg;
3037 struct timeval lastconnecttry;
3040 /* yes, lastconnecttry is really necessary */
3041 lastconnecttry = server->lastconnecttry;
3042 buf = radtcpget(server->sock, 0);
3044 tcpconnect(server, &lastconnecttry, 0, "tcpclientrd");
3048 if (!replyh(server, buf))
3051 server->clientrdgone = 1;
3055 /* code for removing state not finished */
3056 void *clientwr(void *arg) {
3057 struct server *server = (struct server *)arg;
3059 pthread_t clientrdth;
3060 int i, dynconffail = 0;
3063 struct timespec timeout;
3064 struct request statsrvrq;
3065 unsigned char statsrvbuf[38];
3066 struct clsrvconf *conf;
3068 conf = server->conf;
3070 if (server->dynamiclookuparg && !dynamicconfig(server)) {
3075 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
3076 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3080 memset(&timeout, 0, sizeof(struct timespec));
3082 if (conf->statusserver) {
3083 memset(&statsrvrq, 0, sizeof(struct request));
3084 memset(statsrvbuf, 0, sizeof(statsrvbuf));
3085 statsrvbuf[0] = RAD_Status_Server;
3087 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
3088 statsrvbuf[21] = 18;
3089 gettimeofday(&server->lastrcv, NULL);
3092 if (conf->pdef->connecter) {
3093 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
3095 server->connectionok = 1;
3096 if (pthread_create(&clientrdth, NULL, conf->pdef->clientreader, (void *)server)) {
3097 debug(DBG_ERR, "clientwr: pthread_create failed");
3101 server->connectionok = 1;
3104 pthread_mutex_lock(&server->newrq_mutex);
3105 if (!server->newrq) {
3106 gettimeofday(&now, NULL);
3107 /* random 0-7 seconds */
3108 RAND_bytes(&rnd, 1);
3110 if (conf->statusserver) {
3111 if (!timeout.tv_sec || timeout.tv_sec > server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd)
3112 timeout.tv_sec = server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd;
3114 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
3115 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
3118 if (timeout.tv_sec > now.tv_sec)
3119 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
3121 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
3124 if (server->newrq) {
3125 debug(DBG_DBG, "clientwr: got new request");
3130 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
3132 pthread_mutex_unlock(&server->newrq_mutex);
3134 for (i = 0; i < MAX_REQUESTS; i++) {
3135 if (server->clientrdgone) {
3136 pthread_join(clientrdth, NULL);
3139 pthread_mutex_lock(&server->newrq_mutex);
3140 while (i < MAX_REQUESTS && !server->requests[i].buf)
3142 if (i == MAX_REQUESTS) {
3143 pthread_mutex_unlock(&server->newrq_mutex);
3146 rq = server->requests + i;
3149 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
3151 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
3153 /* setting this to NULL means that it can be reused */
3156 pthread_mutex_unlock(&server->newrq_mutex);
3160 gettimeofday(&now, NULL);
3161 if (now.tv_sec < rq->expiry.tv_sec) {
3162 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
3163 timeout.tv_sec = rq->expiry.tv_sec;
3164 pthread_mutex_unlock(&server->newrq_mutex);
3168 if (rq->tries == (*rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
3169 debug(DBG_DBG, "clientwr: removing expired packet from queue");
3170 if (conf->statusserver) {
3171 if (*rq->buf == RAD_Status_Server) {
3172 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
3173 if (server->lostrqs < 255)
3177 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
3178 if (server->lostrqs < 255)
3182 /* setting this to NULL means that it can be reused */
3184 pthread_mutex_unlock(&server->newrq_mutex);
3187 pthread_mutex_unlock(&server->newrq_mutex);
3189 rq->expiry.tv_sec = now.tv_sec + conf->retryinterval;
3190 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
3191 timeout.tv_sec = rq->expiry.tv_sec;
3193 conf->pdef->clientradput(server, server->requests[i].buf);
3195 if (conf->statusserver) {
3196 gettimeofday(&now, NULL);
3197 if (now.tv_sec - server->lastrcv.tv_sec >= STATUS_SERVER_PERIOD) {
3198 if (!RAND_bytes(statsrvbuf + 4, 16)) {
3199 debug(DBG_WARN, "clientwr: failed to generate random auth");
3202 statsrvrq.buf = malloc(sizeof(statsrvbuf));
3203 if (!statsrvrq.buf) {
3204 debug(DBG_ERR, "clientwr: malloc failed");
3207 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
3208 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
3209 sendrq(server, &statsrvrq);
3214 conf->servers = NULL;
3215 if (server->dynamiclookuparg) {
3216 removeserversubrealms(realms, conf);
3220 freeclsrvconf(conf);
3222 freeserver(server, 1);
3223 ERR_remove_state(0);
3227 void *udpserverwr(void *arg) {
3228 struct queue *replyq = udp_server_replyq;
3229 struct reply *reply;
3232 pthread_mutex_lock(&replyq->mutex);
3233 while (!(reply = (struct reply *)list_shift(replyq->entries))) {
3234 debug(DBG_DBG, "udp server writer, waiting for signal");
3235 pthread_cond_wait(&replyq->cond, &replyq->mutex);
3236 debug(DBG_DBG, "udp server writer, got signal");
3238 pthread_mutex_unlock(&replyq->mutex);
3240 if (sendto(reply->toudpsock, reply->buf, RADLEN(reply->buf), 0,
3241 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
3242 debug(DBG_WARN, "sendudp: send failed");
3248 void *udpserverrd(void *arg) {
3250 int *sp = (int *)arg;
3253 memset(&rq, 0, sizeof(struct request));
3254 rq.buf = radudpget(*sp, &rq.from, NULL, &rq.fromsa);
3255 rq.fromudpsock = *sp;
3261 void *tlsserverwr(void *arg) {
3263 unsigned long error;
3264 struct client *client = (struct client *)arg;
3265 struct queue *replyq;
3266 struct reply *reply;
3268 debug(DBG_DBG, "tlsserverwr: starting for %s", client->conf->host);
3269 replyq = client->replyq;
3271 pthread_mutex_lock(&replyq->mutex);
3272 while (!list_first(replyq->entries)) {
3274 debug(DBG_DBG, "tlsserverwr: waiting for signal");
3275 pthread_cond_wait(&replyq->cond, &replyq->mutex);
3276 debug(DBG_DBG, "tlsserverwr: got signal");
3279 /* ssl might have changed while waiting */
3280 pthread_mutex_unlock(&replyq->mutex);
3281 debug(DBG_DBG, "tlsserverwr: exiting as requested");
3282 ERR_remove_state(0);
3286 reply = (struct reply *)list_shift(replyq->entries);
3287 pthread_mutex_unlock(&replyq->mutex);
3288 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
3290 debug(DBG_DBG, "tlsserverwr: sent %d bytes, Radius packet of length %d",
3291 cnt, RADLEN(reply->buf));
3293 while ((error = ERR_get_error()))
3294 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
3300 void tlsserverrd(struct client *client) {
3302 pthread_t tlsserverwrth;
3304 debug(DBG_DBG, "tlsserverrd: starting for %s", client->conf->host);
3306 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
3307 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
3312 memset(&rq, 0, sizeof(struct request));
3313 rq.buf = radtlsget(client->ssl, 0);
3315 debug(DBG_ERR, "tlsserverrd: connection from %s lost", client->conf->host);
3318 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
3321 debug(DBG_ERR, "tlsserverrd: message authentication/validation failed, closing connection from %s", client->conf->host);
3326 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
3328 pthread_mutex_lock(&client->replyq->mutex);
3329 pthread_cond_signal(&client->replyq->cond);
3330 pthread_mutex_unlock(&client->replyq->mutex);
3331 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
3332 pthread_join(tlsserverwrth, NULL);
3333 removeclientrqs(client);
3334 debug(DBG_DBG, "tlsserverrd: reader for %s exiting", client->conf->host);
3337 void *tlsservernew(void *arg) {
3339 struct sockaddr_storage from;
3340 size_t fromlen = sizeof(from);
3341 struct clsrvconf *conf;
3342 struct list_node *cur = NULL;
3345 unsigned long error;
3346 struct client *client;
3349 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
3350 debug(DBG_DBG, "tlsservernew: getpeername failed, exiting");
3353 debug(DBG_WARN, "tlsservernew: incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
3355 conf = find_conf(RAD_TLS, (struct sockaddr *)&from, clconfs, &cur);
3357 ssl = SSL_new(conf->ssl_ctx);
3360 if (SSL_accept(ssl) <= 0) {
3361 while ((error = ERR_get_error()))
3362 debug(DBG_ERR, "tlsservernew: SSL: %s", ERR_error_string(error, NULL));
3363 debug(DBG_ERR, "tlsservernew: SSL_accept failed");
3366 cert = verifytlscert(ssl);
3372 if (verifyconfcert(cert, conf)) {
3374 client = addclient(conf);
3377 tlsserverrd(client);
3378 removeclient(client);
3380 debug(DBG_WARN, "tlsservernew: failed to create new client instance");
3383 conf = find_conf(RAD_TLS, (struct sockaddr *)&from, clconfs, &cur);
3385 debug(DBG_WARN, "tlsservernew: ignoring request, no matching TLS client");
3391 ERR_remove_state(0);
3392 shutdown(s, SHUT_RDWR);
3397 void *tlslistener(void *arg) {
3398 pthread_t tlsserverth;
3399 int s, *sp = (int *)arg;
3400 struct sockaddr_storage from;
3401 size_t fromlen = sizeof(from);
3406 s = accept(*sp, (struct sockaddr *)&from, &fromlen);
3408 debug(DBG_WARN, "accept failed");
3411 if (pthread_create(&tlsserverth, NULL, tlsservernew, (void *)&s)) {
3412 debug(DBG_ERR, "tlslistener: pthread_create failed");
3413 shutdown(s, SHUT_RDWR);
3417 pthread_detach(tlsserverth);
3423 void *tcpserverwr(void *arg) {
3425 struct client *client = (struct client *)arg;
3426 struct queue *replyq;
3427 struct reply *reply;
3429 debug(DBG_DBG, "tcpserverwr: starting for %s", client->conf->host);
3430 replyq = client->replyq;
3432 pthread_mutex_lock(&replyq->mutex);
3433 while (!list_first(replyq->entries)) {
3434 if (client->sock >= 0) {
3435 debug(DBG_DBG, "tcpserverwr: waiting for signal");
3436 pthread_cond_wait(&replyq->cond, &replyq->mutex);
3437 debug(DBG_DBG, "tcpserverwr: got signal");
3439 if (client->sock < 0) {
3440 /* s might have changed while waiting */
3441 pthread_mutex_unlock(&replyq->mutex);
3442 debug(DBG_DBG, "tcpserverwr: exiting as requested");
3446 reply = (struct reply *)list_shift(replyq->entries);
3447 pthread_mutex_unlock(&replyq->mutex);
3448 cnt = write(client->sock, reply->buf, RADLEN(reply->buf));
3450 debug(DBG_DBG, "tcpserverwr: sent %d bytes, Radius packet of length %d",
3451 cnt, RADLEN(reply->buf));
3453 debug(DBG_ERR, "tcpserverwr: write error for %s", client->conf->host);
3459 void tcpserverrd(struct client *client) {
3461 pthread_t tcpserverwrth;
3463 debug(DBG_DBG, "tcpserverrd: starting for %s", client->conf->host);
3465 if (pthread_create(&tcpserverwrth, NULL, tcpserverwr, (void *)client)) {
3466 debug(DBG_ERR, "tcpserverrd: pthread_create failed");
3471 memset(&rq, 0, sizeof(struct request));
3472 rq.buf = radtcpget(client->sock, 0);
3474 debug(DBG_ERR, "tcpserverrd: connection from %s lost", client->conf->host);
3477 debug(DBG_DBG, "tcpserverrd: got Radius message from %s", client->conf->host);
3480 debug(DBG_ERR, "tcpserverrd: message authentication/validation failed, closing connection from %s", client->conf->host);
3485 /* stop writer by setting s to -1 and give signal in case waiting for data */
3487 pthread_mutex_lock(&client->replyq->mutex);
3488 pthread_cond_signal(&client->replyq->cond);
3489 pthread_mutex_unlock(&client->replyq->mutex);
3490 debug(DBG_DBG, "tcpserverrd: waiting for writer to end");
3491 pthread_join(tcpserverwrth, NULL);
3492 removeclientrqs(client);
3493 debug(DBG_DBG, "tcpserverrd: reader for %s exiting", client->conf->host);
3496 void *tcpservernew(void *arg) {
3498 struct sockaddr_storage from;
3499 size_t fromlen = sizeof(from);
3500 struct clsrvconf *conf;
3501 struct client *client;
3504 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
3505 debug(DBG_DBG, "tcpservernew: getpeername failed, exiting");
3508 debug(DBG_WARN, "tcpservernew: incoming TCP connection from %s", addr2string((struct sockaddr *)&from, fromlen));
3510 conf = find_conf(RAD_TCP, (struct sockaddr *)&from, clconfs, NULL);
3512 client = addclient(conf);
3515 tcpserverrd(client);
3516 removeclient(client);
3518 debug(DBG_WARN, "tcpservernew: failed to create new client instance");
3520 debug(DBG_WARN, "tcpservernew: ignoring request, no matching TCP client");
3523 shutdown(s, SHUT_RDWR);
3528 void *tcplistener(void *arg) {
3529 pthread_t tcpserverth;
3530 int s, *sp = (int *)arg;
3531 struct sockaddr_storage from;
3532 size_t fromlen = sizeof(from);
3537 s = accept(*sp, (struct sockaddr *)&from, &fromlen);
3539 debug(DBG_WARN, "accept failed");
3542 if (pthread_create(&tcpserverth, NULL, tcpservernew, (void *)&s)) {
3543 debug(DBG_ERR, "tcplistener: pthread_create failed");
3544 shutdown(s, SHUT_RDWR);
3548 pthread_detach(tcpserverth);
3554 void createlistener(uint8_t type, char *arg) {
3556 struct clsrvconf *listenres;
3557 struct addrinfo *res;
3558 int s = -1, on = 1, *sp = NULL;
3560 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
3562 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
3564 for (res = listenres->addrinfo; res; res = res->ai_next) {
3565 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
3567 debug(DBG_WARN, "createlistener: socket failed");
3570 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
3572 if (res->ai_family == AF_INET6)
3573 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
3575 if (bind(s, res->ai_addr, res->ai_addrlen)) {
3576 debug(DBG_WARN, "createlistener: bind failed");
3582 sp = malloc(sizeof(int));
3584 debugx(1, DBG_ERR, "malloc failed");
3586 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
3587 debugx(1, DBG_ERR, "pthread_create failed");
3591 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
3593 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
3594 listenres->host ? listenres->host : "*", listenres->port);
3595 freeclsrvres(listenres);
3598 void createlisteners(uint8_t type, char **args) {
3602 for (i = 0; args[i]; i++)
3603 createlistener(type, args[i]);
3605 createlistener(type, NULL);
3609 void ssl_info_callback(const SSL *ssl, int where, int ret) {
3613 w = where & ~SSL_ST_MASK;
3615 if (w & SSL_ST_CONNECT)
3617 else if (w & SSL_ST_ACCEPT)
3622 if (where & SSL_CB_LOOP)
3623 debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
3624 else if (where & SSL_CB_ALERT) {
3625 s = (where & SSL_CB_READ) ? "read" : "write";
3626 debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
3628 else if (where & SSL_CB_EXIT) {
3630 debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
3632 debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
3637 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
3638 SSL_CTX *ctx = NULL;
3639 STACK_OF(X509_NAME) *calist;
3642 unsigned long error;
3645 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
3646 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
3647 for (i = 0; i < CRYPTO_num_locks(); i++) {
3648 ssl_lock_count[i] = 0;
3649 pthread_mutex_init(&ssl_locks[i], NULL);
3651 CRYPTO_set_id_callback(ssl_thread_id);
3652 CRYPTO_set_locking_callback(ssl_locking_callback);
3654 SSL_load_error_strings();
3657 while (!RAND_status()) {
3658 time_t t = time(NULL);
3659 pid_t pid = getpid();
3660 RAND_seed((unsigned char *)&t, sizeof(time_t));
3661 RAND_seed((unsigned char *)&pid, sizeof(pid));
3667 ctx = SSL_CTX_new(TLSv1_method());
3669 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
3673 ctx = SSL_CTX_new(DTLSv1_method());
3675 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
3677 SSL_CTX_set_read_ahead(ctx, 1);
3681 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
3685 if (conf->certkeypwd) {
3686 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
3687 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
3689 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
3690 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
3691 !SSL_CTX_check_private_key(ctx) ||
3692 !SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
3693 while ((error = ERR_get_error()))
3694 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
3695 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
3700 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
3701 if (!conf->cacertfile || calist) {
3702 if (conf->cacertpath) {
3704 calist = sk_X509_NAME_new_null();
3705 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
3706 sk_X509_NAME_free(calist);
3712 while ((error = ERR_get_error()))
3713 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
3714 debug(DBG_ERR, "tlscreatectx: Error adding CA subjects in TLS context %s", conf->name);
3718 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
3719 SSL_CTX_set_client_CA_list(ctx, calist);
3721 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
3722 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
3724 if (conf->crlcheck) {
3725 x509_s = SSL_CTX_get_cert_store(ctx);
3726 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
3729 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
3733 SSL_CTX *tlsgetctx(uint8_t type, char *alt1, char *alt2) {
3734 struct list_node *entry;
3735 struct tls *t, *t1 = NULL, *t2 = NULL;
3736 SSL_CTX *ctx = NULL;
3738 pthread_mutex_lock(&tlsconfs_lock);
3740 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
3741 t = (struct tls *)entry->data;
3742 if (!strcasecmp(t->name, alt1)) {
3746 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
3757 t->tlsctx = tlscreatectx(RAD_TLS, t);
3762 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
3768 pthread_mutex_unlock(&tlsconfs_lock);
3772 struct list *addsrvconfs(char *value, char **names) {
3773 struct list *conflist;
3775 struct list_node *entry;
3776 struct clsrvconf *conf = NULL;
3778 if (!names || !*names)
3781 conflist = list_create();
3783 debug(DBG_ERR, "malloc failed");
3787 for (n = 0; names[n]; n++) {
3788 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3789 conf = (struct clsrvconf *)entry->data;
3790 if (!strcasecmp(names[n], conf->name))
3794 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
3795 list_destroy(conflist);
3798 if (!list_push(conflist, conf)) {
3799 debug(DBG_ERR, "malloc failed");
3800 list_destroy(conflist);
3803 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
3808 void freerealm(struct realm *realm) {
3812 free(realm->message);
3813 regfree(&realm->regex);
3814 pthread_mutex_destroy(&realm->subrealms_mutex);
3815 if (realm->subrealms)
3816 list_destroy(realm->subrealms);
3817 if (realm->srvconfs) {
3818 /* emptying list without freeing data */
3819 while (list_shift(realm->srvconfs));
3820 list_destroy(realm->srvconfs);
3822 if (realm->accsrvconfs) {
3823 /* emptying list without freeing data */
3824 while (list_shift(realm->accsrvconfs));
3825 list_destroy(realm->accsrvconfs);
3830 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
3832 struct realm *realm;
3833 char *s, *regex = NULL;
3835 if (*value == '/') {
3836 /* regexp, remove optional trailing / if present */
3837 if (value[strlen(value) - 1] == '/')
3838 value[strlen(value) - 1] = '\0';
3840 /* not a regexp, let us make it one */
3841 if (*value == '*' && !value[1])
3842 regex = stringcopy(".*", 0);
3844 for (n = 0, s = value; *s;)
3847 regex = malloc(strlen(value) + n + 3);
3850 for (n = 1, s = value; *s; s++) {
3860 debug(DBG_ERR, "malloc failed");
3864 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
3867 realm = malloc(sizeof(struct realm));
3869 debug(DBG_ERR, "malloc failed");
3872 memset(realm, 0, sizeof(struct realm));
3874 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
3875 debug(DBG_ERR, "mutex init failed");
3881 realm->name = stringcopy(value, 0);
3883 debug(DBG_ERR, "malloc failed");
3886 if (message && strlen(message) > 253) {
3887 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
3890 realm->message = message;
3891 realm->accresp = accresp;
3893 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
3894 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
3898 if (servers && *servers) {
3899 realm->srvconfs = addsrvconfs(value, servers);
3900 if (!realm->srvconfs)
3904 if (accservers && *accservers) {
3905 realm->accsrvconfs = addsrvconfs(value, accservers);
3906 if (!realm->accsrvconfs)
3910 if (!list_push(realmlist, realm)) {
3911 debug(DBG_ERR, "malloc failed");
3912 pthread_mutex_destroy(&realm->subrealms_mutex);
3916 debug(DBG_DBG, "addrealm: added realm %s", value);
3926 for (n = 0; servers[n]; n++)
3931 for (n = 0; accservers[n]; n++)
3932 free(accservers[n]);
3938 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
3939 struct clsrvconf *srvconf;
3940 struct realm *newrealm = NULL;
3941 char *realmname, *s;
3944 if (!conf->dynamiclookupcommand)
3947 /* create dynamic for the realm (string after last @, exit if nothing after @ */
3948 realmname = strrchr(id, '@');
3954 for (s = realmname; *s; s++)
3955 if (*s != '.' && *s != '-' && !isalnum((int)*s))
3958 pthread_mutex_lock(&realm->subrealms_mutex);
3959 /* exit if we now already got a matching subrealm */
3960 if (id2realm(realm->subrealms, id))
3962 srvconf = malloc(sizeof(struct clsrvconf));
3964 debug(DBG_ERR, "malloc failed");
3968 if (!addserver(srvconf))
3971 if (!realm->subrealms)
3972 realm->subrealms = list_create();
3973 if (!realm->subrealms)
3975 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
3979 /* add server and accserver to newrealm */
3980 newrealm->srvconfs = list_create();
3981 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
3982 debug(DBG_ERR, "malloc failed");
3985 newrealm->accsrvconfs = list_create();
3986 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
3987 debug(DBG_ERR, "malloc failed");
3991 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
3993 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
3994 debug(DBG_ERR, "pthread_create failed");
3997 pthread_detach(clientth);
4002 list_removedata(realm->subrealms, newrealm);
4003 freerealm(newrealm);
4004 if (!list_first(realm->subrealms)) {
4005 list_destroy(realm->subrealms);
4006 realm->subrealms = NULL;
4009 freeserver(srvconf->servers, 1);
4011 debug(DBG_ERR, "failed to create dynamic server");
4014 pthread_mutex_unlock(&realm->subrealms_mutex);
4017 int dynamicconfig(struct server *server) {
4018 int ok, fd[2], status;
4020 struct clsrvconf *conf = server->conf;
4021 struct gconffile *cf = NULL;
4023 /* for now we only learn hostname/address */
4024 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
4027 debug(DBG_ERR, "dynamicconfig: pipe error");
4032 debug(DBG_ERR, "dynamicconfig: fork error");
4036 } else if (pid == 0) {
4039 if (fd[1] != STDOUT_FILENO) {
4040 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
4041 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
4044 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
4045 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
4049 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
4050 ok = getgenericconfig(&cf, NULL,
4051 "Server", CONF_CBK, confserver_cb, (void *)conf,
4056 if (waitpid(pid, &status, 0) < 0) {
4057 debug(DBG_ERR, "dynamicconfig: wait error");
4062 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
4070 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
4074 int addmatchcertattr(struct clsrvconf *conf) {
4078 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
4079 r = &conf->certcnregex;
4080 v = conf->matchcertattr + 4;
4081 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
4082 r = &conf->certuriregex;
4083 v = conf->matchcertattr + 20;
4088 /* regexp, remove optional trailing / if present */
4089 if (v[strlen(v) - 1] == '/')
4090 v[strlen(v) - 1] = '\0';
4094 *r = malloc(sizeof(regex_t));
4096 debug(DBG_ERR, "malloc failed");
4099 if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
4102 debug(DBG_ERR, "failed to compile regular expression %s", v);
4108 int addrewriteattr(struct clsrvconf *conf) {
4111 v = conf->rewriteattr + 11;
4112 if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
4114 /* regexp, remove optional trailing / if present */
4115 if (v[strlen(v) - 1] == '/')
4116 v[strlen(v) - 1] = '\0';
4124 conf->rewriteattrregex = malloc(sizeof(regex_t));
4125 if (!conf->rewriteattrregex) {
4126 debug(DBG_ERR, "malloc failed");
4130 conf->rewriteattrreplacement = stringcopy(w, 0);
4131 if (!conf->rewriteattrreplacement) {
4132 free(conf->rewriteattrregex);
4133 conf->rewriteattrregex = NULL;
4137 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
4138 free(conf->rewriteattrregex);
4139 conf->rewriteattrregex = NULL;
4140 free(conf->rewriteattrreplacement);
4141 conf->rewriteattrreplacement = NULL;
4142 debug(DBG_ERR, "failed to compile regular expression %s", v);
4149 /* should accept both names and numeric values, only numeric right now */
4150 uint8_t attrname2val(char *attrname) {
4153 val = atoi(attrname);
4154 return val > 0 && val < 256 ? val : 0;
4157 /* should accept both names and numeric values, only numeric right now */
4158 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
4161 *vendor = atoi(attrname);
4162 s = strchr(attrname, ':');
4167 *type = atoi(s + 1);
4168 return *type >= 0 && *type < 256;
4171 struct rewrite *getrewrite(char *alt1, char *alt2) {
4172 struct list_node *entry;
4173 struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
4175 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
4176 r = (struct rewriteconf *)entry->data;
4177 if (!strcasecmp(r->name, alt1)) {
4181 if (!r2 && alt2 && !strcasecmp(r->name, alt2))
4191 void addrewrite(char *value, char **attrs, char **vattrs) {
4192 struct rewriteconf *new;
4193 struct rewrite *rewrite = NULL;
4196 uint32_t *p, *va = NULL;
4200 for (; attrs[n]; n++);
4201 a = malloc((n + 1) * sizeof(uint8_t));
4203 debugx(1, DBG_ERR, "malloc failed");
4205 for (i = 0; i < n; i++) {
4206 if (!(a[i] = attrname2val(attrs[i])))
4207 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
4216 for (; vattrs[n]; n++);
4217 va = malloc((2 * n + 1) * sizeof(uint32_t));
4219 debugx(1, DBG_ERR, "malloc failed");
4221 for (p = va, i = 0; i < n; i++, p += 2) {
4222 if (!vattrname2val(vattrs[i], p, p + 1))
4223 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
4231 rewrite = malloc(sizeof(struct rewrite));
4233 debugx(1, DBG_ERR, "malloc failed");
4234 rewrite->removeattrs = a;
4235 rewrite->removevendorattrs = va;
4238 new = malloc(sizeof(struct rewriteconf));
4239 if (!new || !list_push(rewriteconfs, new))
4240 debugx(1, DBG_ERR, "malloc failed");
4242 memset(new, 0, sizeof(struct rewriteconf));
4243 new->name = stringcopy(value, 0);
4245 debugx(1, DBG_ERR, "malloc failed");
4247 new->rewrite = rewrite;
4248 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
4251 void freeclsrvconf(struct clsrvconf *conf) {
4257 free(conf->matchcertattr);
4258 if (conf->certcnregex)
4259 regfree(conf->certcnregex);
4260 if (conf->certuriregex)
4261 regfree(conf->certuriregex);
4262 free(conf->confrewrite);
4263 free(conf->rewriteattr);
4264 if (conf->rewriteattrregex)
4265 regfree(conf->rewriteattrregex);
4266 free(conf->rewriteattrreplacement);
4267 free(conf->dynamiclookupcommand);
4268 free(conf->rewrite);
4270 freeaddrinfo(conf->addrinfo);
4271 /* not touching ssl_ctx, clients and servers */
4275 int mergeconfstring(char **dst, char **src) {
4284 t = stringcopy(*dst, 0);
4286 debug(DBG_ERR, "malloc failed");
4294 /* assumes dst is a shallow copy */
4295 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
4296 if (!mergeconfstring(&dst->name, &src->name) ||
4297 !mergeconfstring(&dst->host, &src->host) ||
4298 !mergeconfstring(&dst->port, &src->port) ||
4299 !mergeconfstring(&dst->secret, &src->secret) ||
4300 !mergeconfstring(&dst->tls, &src->tls) ||
4301 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
4302 !mergeconfstring(&dst->confrewrite, &src->confrewrite) ||
4303 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
4306 dst->pdef = src->pdef;
4307 dst->statusserver = src->statusserver;
4308 dst->certnamecheck = src->certnamecheck;
4309 if (src->retryinterval != 255)
4310 dst->retryinterval = src->retryinterval;
4311 if (src->retrycount != 255)
4312 dst->retrycount = src->retrycount;
4316 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4317 struct clsrvconf *conf;
4318 char *conftype = NULL;
4320 debug(DBG_DBG, "confclient_cb called for %s", block);
4322 conf = malloc(sizeof(struct clsrvconf));
4323 if (!conf || !list_push(clconfs, conf))
4324 debugx(1, DBG_ERR, "malloc failed");
4325 memset(conf, 0, sizeof(struct clsrvconf));
4326 conf->certnamecheck = 1;
4328 if (!getgenericconfig(cf, block,
4329 "type", CONF_STR, &conftype,
4330 "host", CONF_STR, &conf->host,
4331 "secret", CONF_STR, &conf->secret,
4332 "tls", CONF_STR, &conf->tls,
4333 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
4334 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
4335 "rewrite", CONF_STR, &conf->confrewrite,
4336 "rewriteattribute", CONF_STR, &conf->rewriteattr,
4339 debugx(1, DBG_ERR, "configuration error");
4341 conf->name = stringcopy(val, 0);
4343 conf->host = stringcopy(val, 0);
4344 if (!conf->name || !conf->host)
4345 debugx(1, DBG_ERR, "malloc failed");
4348 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
4349 conf->type = protoname2int(conftype);
4350 conf->pdef = &protodefs[conf->type];
4351 if (!conf->pdef->name)
4352 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
4355 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
4356 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultclient", "default");
4358 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
4359 if (conf->matchcertattr && !addmatchcertattr(conf))
4360 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
4363 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
4365 if (conf->rewriteattr) {
4366 if (!addrewriteattr(conf))
4367 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
4370 if (!resolvepeer(conf, 0))
4371 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
4373 if (!conf->secret) {
4374 if (!conf->pdef->secretdefault)
4375 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
4376 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
4378 debugx(1, DBG_ERR, "malloc failed");
4383 int compileserverconfig(struct clsrvconf *conf, const char *block) {
4384 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
4385 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultserver", "default");
4386 if (!conf->ssl_ctx) {
4387 debug(DBG_ERR, "error in block %s, no tls context defined", block);
4390 if (conf->matchcertattr && !addmatchcertattr(conf)) {
4391 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
4397 conf->port = stringcopy(conf->pdef->portdefault, 0);
4399 debug(DBG_ERR, "malloc failed");
4404 if (conf->retryinterval == 255)
4405 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
4406 if (conf->retrycount == 255)
4407 conf->retrycount = protodefs[conf->type].retrycountdefault;
4409 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
4411 if (!conf->secret) {
4412 if (!conf->pdef->secretdefault) {
4413 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
4416 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
4417 if (!conf->secret) {
4418 debug(DBG_ERR, "malloc failed");
4423 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
4424 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
4430 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4431 struct clsrvconf *conf, *resconf;
4432 char *conftype = NULL;
4433 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
4435 debug(DBG_DBG, "confserver_cb called for %s", block);
4437 conf = malloc(sizeof(struct clsrvconf));
4439 debug(DBG_ERR, "malloc failed");
4442 memset(conf, 0, sizeof(struct clsrvconf));
4443 resconf = (struct clsrvconf *)arg;
4445 conf->statusserver = resconf->statusserver;
4446 conf->certnamecheck = resconf->certnamecheck;
4448 conf->certnamecheck = 1;
4450 if (!getgenericconfig(cf, block,
4451 "type", CONF_STR, &conftype,
4452 "host", CONF_STR, &conf->host,
4453 "port", CONF_STR, &conf->port,
4454 "secret", CONF_STR, &conf->secret,
4455 "tls", CONF_STR, &conf->tls,
4456 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
4457 "rewrite", CONF_STR, &conf->confrewrite,
4458 "StatusServer", CONF_BLN, &conf->statusserver,
4459 "RetryInterval", CONF_LINT, &retryinterval,
4460 "RetryCount", CONF_LINT, &retrycount,
4461 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
4462 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
4465 debug(DBG_ERR, "configuration error");
4469 conf->name = stringcopy(val, 0);
4471 debug(DBG_ERR, "malloc failed");
4475 conf->host = stringcopy(val, 0);
4477 debug(DBG_ERR, "malloc failed");
4483 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
4484 conf->type = protoname2int(conftype);
4485 conf->pdef = &protodefs[conf->type];
4486 if (!conf->pdef->name) {
4487 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
4493 if (retryinterval != LONG_MIN) {
4494 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
4495 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
4498 conf->retryinterval = (uint8_t)retryinterval;
4500 conf->retryinterval = 255;
4502 if (retrycount != LONG_MIN) {
4503 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
4504 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
4507 conf->retrycount = (uint8_t)retrycount;
4509 conf->retrycount = 255;
4512 if (!mergesrvconf(resconf, conf))
4516 if (conf->dynamiclookupcommand) {
4517 free(conf->dynamiclookupcommand);
4518 conf->dynamiclookupcommand = NULL;
4522 if (resconf || !conf->dynamiclookupcommand) {
4523 if (!compileserverconfig(conf, block))
4530 if (!list_push(srvconfs, conf)) {
4531 debug(DBG_ERR, "malloc failed");
4537 freeclsrvconf(conf);
4541 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4542 char **servers = NULL, **accservers = NULL, *msg = NULL;
4543 uint8_t accresp = 0;
4545 debug(DBG_DBG, "confrealm_cb called for %s", block);
4547 if (!getgenericconfig(cf, block,
4548 "server", CONF_MSTR, &servers,
4549 "accountingServer", CONF_MSTR, &accservers,
4550 "ReplyMessage", CONF_STR, &msg,
4551 "AccountingResponse", CONF_BLN, &accresp,
4554 debugx(1, DBG_ERR, "configuration error");
4556 addrealm(realms, val, servers, accservers, msg, accresp);
4560 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4563 debug(DBG_DBG, "conftls_cb called for %s", block);
4565 conf = malloc(sizeof(struct tls));
4567 debug(DBG_ERR, "conftls_cb: malloc failed");
4570 memset(conf, 0, sizeof(struct tls));
4572 if (!getgenericconfig(cf, block,
4573 "CACertificateFile", CONF_STR, &conf->cacertfile,
4574 "CACertificatePath", CONF_STR, &conf->cacertpath,
4575 "CertificateFile", CONF_STR, &conf->certfile,
4576 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
4577 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
4578 "CRLCheck", CONF_BLN, &conf->crlcheck,
4581 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
4584 if (!conf->certfile || !conf->certkeyfile) {
4585 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
4588 if (!conf->cacertfile && !conf->cacertpath) {
4589 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
4593 conf->name = stringcopy(val, 0);
4595 debug(DBG_ERR, "conftls_cb: malloc failed");
4599 pthread_mutex_lock(&tlsconfs_lock);
4600 if (!list_push(tlsconfs, conf)) {
4601 debug(DBG_ERR, "conftls_cb: malloc failed");
4602 pthread_mutex_unlock(&tlsconfs_lock);
4605 pthread_mutex_unlock(&tlsconfs_lock);
4607 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
4611 free(conf->cacertfile);
4612 free(conf->cacertpath);
4613 free(conf->certfile);
4614 free(conf->certkeyfile);
4615 free(conf->certkeypwd);
4620 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4621 char **attrs = NULL, **vattrs = NULL;
4623 debug(DBG_DBG, "confrewrite_cb called for %s", block);
4625 if (!getgenericconfig(cf, block,
4626 "removeAttribute", CONF_MSTR, &attrs,
4627 "removeVendorAttribute", CONF_MSTR, &vattrs,
4630 debugx(1, DBG_ERR, "configuration error");
4631 addrewrite(val, attrs, vattrs);
4635 void getmainconfig(const char *configfile) {
4636 long int loglevel = LONG_MIN;
4637 struct gconffile *cfs;
4639 cfs = openconfigfile(configfile);
4640 memset(&options, 0, sizeof(options));
4642 clconfs = list_create();
4644 debugx(1, DBG_ERR, "malloc failed");
4646 srvconfs = list_create();
4648 debugx(1, DBG_ERR, "malloc failed");
4650 realms = list_create();
4652 debugx(1, DBG_ERR, "malloc failed");
4654 tlsconfs = list_create();
4656 debugx(1, DBG_ERR, "malloc failed");
4658 rewriteconfs = list_create();
4660 debugx(1, DBG_ERR, "malloc failed");
4662 if (!getgenericconfig(&cfs, NULL,
4663 "ListenUDP", CONF_MSTR, &options.listenudp,
4664 "ListenTCP", CONF_MSTR, &options.listentcp,
4665 "ListenTLS", CONF_MSTR, &options.listentls,
4666 "ListenDTLS", CONF_MSTR, &options.listendtls,
4667 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
4668 "SourceUDP", CONF_STR, &options.sourceudp,
4669 "SourceTCP", CONF_STR, &options.sourcetcp,
4670 "SourceTLS", CONF_STR, &options.sourcetls,
4671 "SourceDTLS", CONF_STR, &options.sourcedtls,
4672 "LogLevel", CONF_LINT, &loglevel,
4673 "LogDestination", CONF_STR, &options.logdestination,
4674 "LoopPrevention", CONF_BLN, &options.loopprevention,
4675 "Client", CONF_CBK, confclient_cb, NULL,
4676 "Server", CONF_CBK, confserver_cb, NULL,
4677 "Realm", CONF_CBK, confrealm_cb, NULL,
4678 "TLS", CONF_CBK, conftls_cb, NULL,
4679 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
4682 debugx(1, DBG_ERR, "configuration error");
4684 if (loglevel != LONG_MIN) {
4685 if (loglevel < 1 || loglevel > 4)
4686 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
4687 options.loglevel = (uint8_t)loglevel;
4691 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
4694 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
4697 *configfile = optarg;
4700 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
4701 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
4702 *loglevel = *optarg - '0';
4711 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
4716 if (!(argc - optind))
4720 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
4724 int daemon(int a, int b) {
4732 for (i = 0; i < 3; i++) {
4734 open("/dev/null", O_RDWR);
4740 void *sighandler(void *arg) {
4745 sigemptyset(&sigset);
4746 sigaddset(&sigset, SIGPIPE);
4747 sigwait(&sigset, &sig);
4748 /* only get SIGPIPE right now, so could simplify below code */
4751 /* completely ignoring this */
4754 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
4757 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
4762 int main(int argc, char **argv) {
4763 pthread_t sigth, udpclient4rdth, udpclient6rdth, udpserverwrth, dtlsclient4rdth, dtlsclient6rdth;
4765 struct list_node *entry;
4766 uint8_t foreground = 0, pretend = 0, loglevel = 0;
4767 char *configfile = NULL;
4768 struct clsrvconf *srvconf;
4770 debug_init("radsecproxy");
4771 debug_set_level(DEBUG_LEVEL);
4772 pthread_mutex_init(&tlsconfs_lock, NULL);
4774 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
4776 debug_set_level(loglevel);
4777 getmainconfig(configfile ? configfile : CONFIG_MAIN);
4779 options.loglevel = loglevel;
4780 else if (options.loglevel)
4781 debug_set_level(options.loglevel);
4783 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
4784 free(options.logdestination);
4786 if (!list_first(clconfs))
4787 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
4788 if (!list_first(realms))
4789 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
4792 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
4794 if (!foreground && (daemon(0, 0) < 0))
4795 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
4797 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
4799 sigemptyset(&sigset);
4800 /* exit on all but SIGPIPE, ignore more? */
4801 sigaddset(&sigset, SIGPIPE);
4802 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
4803 pthread_create(&sigth, NULL, sighandler, NULL);
4805 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
4806 srvconf = (struct clsrvconf *)entry->data;
4807 if (srvconf->dynamiclookupcommand)
4809 if (!addserver(srvconf))
4810 debugx(1, DBG_ERR, "failed to add server");
4811 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
4812 (void *)(srvconf->servers)))
4813 debugx(1, DBG_ERR, "pthread_create failed");
4815 /* srcprotores for UDP no longer needed */
4816 if (srcprotores[RAD_UDP]) {
4817 freeaddrinfo(srcprotores[RAD_UDP]);
4818 srcprotores[RAD_UDP] = NULL;
4821 if (udp_client4_sock >= 0)
4822 if (pthread_create(&udpclient4rdth, NULL, protodefs[RAD_UDP].clientreader, (void *)&udp_client4_sock))
4823 debugx(1, DBG_ERR, "pthread_create failed");
4824 if (udp_client6_sock >= 0)
4825 if (pthread_create(&udpclient6rdth, NULL, protodefs[RAD_UDP].clientreader, (void *)&udp_client6_sock))
4826 debugx(1, DBG_ERR, "pthread_create failed");
4828 if (dtls_client4_sock >= 0)
4829 if (pthread_create(&dtlsclient4rdth, NULL, udpdtlsclientrd, (void *)&dtls_client4_sock))
4830 debugx(1, DBG_ERR, "pthread_create failed");
4831 if (dtls_client6_sock >= 0)
4832 if (pthread_create(&dtlsclient6rdth, NULL, udpdtlsclientrd, (void *)&dtls_client6_sock))
4833 debugx(1, DBG_ERR, "pthread_create failed");
4835 if (find_conf_type(RAD_TCP, clconfs, NULL))
4836 createlisteners(RAD_TCP, options.listentcp);
4838 if (find_conf_type(RAD_TLS, clconfs, NULL))
4839 createlisteners(RAD_TLS, options.listentls);
4841 if (find_conf_type(RAD_DTLS, clconfs, NULL))
4842 createlisteners(RAD_DTLS, options.listendtls);
4844 if (find_conf_type(RAD_UDP, clconfs, NULL)) {
4845 udp_server_replyq = newqueue();
4846 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
4847 debugx(1, DBG_ERR, "pthread_create failed");
4848 createlisteners(RAD_UDP, options.listenudp);
4849 if (options.listenaccudp)
4850 createlisteners(RAD_UDP, options.listenaccudp);
4853 /* just hang around doing nothing, anything to do here? */