2 * Copyright (C) 2006-2008 Stig Venaas <venaas@uninett.no>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
9 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
10 * rd is responsible for init and launching wr
11 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
12 * each tlsserverrd launches tlsserverwr
13 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
14 * for init and launching rd
16 * serverrd will receive a request, processes it and puts it in the requestq of
17 * the appropriate clientwr
18 * clientwr monitors its requestq and sends requests
19 * clientrd looks for responses, processes them and puts them in the replyq of
20 * the peer the request came from
21 * serverwr monitors its reply and sends replies
23 * In addition to the main thread, we have:
24 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
25 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
26 * For each TLS peer connecting to us there will be 2 more TLS threads
27 * This is only for connected peers
28 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
29 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
33 #include <sys/socket.h>
34 #include <netinet/in.h>
42 #include <sys/types.h>
44 #include <arpa/inet.h>
48 #include <openssl/ssl.h>
49 #include <openssl/rand.h>
50 #include <openssl/err.h>
51 #include <openssl/md5.h>
52 #include <openssl/hmac.h>
53 #include <openssl/x509v3.h>
58 #include "radsecproxy.h"
60 static struct options options;
61 struct list *clconfs, *srvconfs, *realms, *tlsconfs, *rewriteconfs;
63 static int client_udp_count = 0;
64 static int client_tls_count = 0;
65 static int server_udp_count = 0;
66 static int server_tls_count = 0;
68 static struct addrinfo *srcudpres = NULL;
69 static struct addrinfo *srctcpres = NULL;
71 static struct replyq *udp_server_replyq = NULL;
72 static int udp_server_sock = -1;
73 static int udp_accserver_sock = -1;
74 static int udp_client4_sock = -1;
75 static int udp_client6_sock = -1;
76 static pthread_mutex_t *ssl_locks;
77 static long *ssl_lock_count;
81 /* minimum required declarations to avoid reordering code */
82 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
83 void dynamicconfig(struct server *server);
85 /* callbacks for making OpenSSL thread safe */
86 unsigned long ssl_thread_id() {
87 return (unsigned long)pthread_self();
90 void ssl_locking_callback(int mode, int type, const char *file, int line) {
91 if (mode & CRYPTO_LOCK) {
92 pthread_mutex_lock(&ssl_locks[type]);
93 ssl_lock_count[type]++;
95 pthread_mutex_unlock(&ssl_locks[type]);
98 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
99 int pwdlen = strlen(userdata);
100 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
102 memcpy(buf, userdata, pwdlen);
106 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
111 err_cert = X509_STORE_CTX_get_current_cert(ctx);
112 err = X509_STORE_CTX_get_error(ctx);
113 depth = X509_STORE_CTX_get_error_depth(ctx);
115 if (depth > MAX_CERT_DEPTH) {
117 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
118 X509_STORE_CTX_set_error(ctx, err);
122 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
123 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
126 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
127 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
128 debug(DBG_WARN, "\tIssuer=%s", buf);
130 case X509_V_ERR_CERT_NOT_YET_VALID:
131 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
132 debug(DBG_WARN, "\tCertificate not yet valid");
134 case X509_V_ERR_CERT_HAS_EXPIRED:
135 debug(DBG_WARN, "Certificate has expired");
137 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
138 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
143 printf("certificate verify returns %d\n", ok);
148 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
149 struct addrinfo hints, *addrinfo, *res;
153 slash = conf->host ? strchr(conf->host, '/') : NULL;
157 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
161 if (*s < '0' || *s > '9') {
162 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
165 plen = atoi(slash + 1);
166 if (plen < 0 || plen > 128) {
167 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
172 memset(&hints, 0, sizeof(hints));
173 hints.ai_socktype = (conf->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
174 hints.ai_family = AF_UNSPEC;
175 hints.ai_flags = ai_flags;
176 if (!conf->host && !conf->port) {
177 /* getaddrinfo() doesn't like host and port to be NULL */
178 if (getaddrinfo(conf->host, DEFAULT_UDP_PORT, &hints, &addrinfo)) {
179 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
182 for (res = addrinfo; res; res = res->ai_next) {
183 switch (res->ai_family) {
185 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
188 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
194 hints.ai_flags |= AI_NUMERICHOST;
195 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
196 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
201 switch (addrinfo->ai_family) {
204 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
205 freeaddrinfo(addrinfo);
212 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
213 freeaddrinfo(addrinfo);
216 conf->prefixlen = plen;
218 conf->prefixlen = 255;
221 freeaddrinfo(conf->addrinfo);
222 conf->addrinfo = addrinfo;
226 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
228 struct addrinfo *res;
230 for (res = addrinfo; res; res = res->ai_next) {
231 if (family != AF_UNSPEC && family != res->ai_family)
233 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
235 debug(DBG_WARN, "bindtoaddr: socket failed");
239 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
242 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
245 if (!bind(s, res->ai_addr, res->ai_addrlen))
247 debug(DBG_WARN, "bindtoaddr: bind failed");
253 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
258 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
262 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
264 debugx(1, DBG_ERR, "no ] matching initial [");
268 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
271 debugx(1, DBG_ERR, "missing host/address");
273 conf->host = stringcopy(field, p - field);
276 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
277 debugx(1, DBG_ERR, "unexpected character after ]");
280 /* port number or service name is specified */;
282 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
284 debugx(1, DBG_ERR, "syntax error, : but no following port");
285 conf->port = stringcopy(field, p - field);
287 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
291 struct clsrvconf *resolve_hostport(char type, char *lconf, char *default_port) {
292 struct clsrvconf *conf;
294 conf = malloc(sizeof(struct clsrvconf));
296 debugx(1, DBG_ERR, "malloc failed");
297 memset(conf, 0, sizeof(struct clsrvconf));
300 parsehostport(lconf, conf, default_port);
301 if (!strcmp(conf->host, "*")) {
306 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
307 if (!resolvepeer(conf, AI_PASSIVE))
308 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
312 void freeclsrvres(struct clsrvconf *res) {
316 freeaddrinfo(res->addrinfo);
320 int connecttcp(struct addrinfo *addrinfo) {
322 struct addrinfo *res;
325 for (res = addrinfo; res; res = res->ai_next) {
326 s = bindtoaddr(srctcpres, res->ai_family, 1, 1);
328 debug(DBG_WARN, "connecttoserver: socket failed");
331 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
333 debug(DBG_WARN, "connecttoserver: connect failed");
340 /* returns 1 if the len first bits are equal, else 0 */
341 int prefixmatch(void *a1, void *a2, uint8_t len) {
342 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
344 if (l && memcmp(a1, a2, l))
349 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
352 /* check if conf has matching address */
353 struct clsrvconf *checkconfaddr(char type, struct sockaddr *addr, struct clsrvconf *conf) {
354 struct sockaddr_in6 *sa6 = NULL;
355 struct in_addr *a4 = NULL;
356 struct addrinfo *res;
358 if (addr->sa_family == AF_INET6) {
359 sa6 = (struct sockaddr_in6 *)addr;
360 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
361 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
365 a4 = &((struct sockaddr_in *)addr)->sin_addr;
367 if (conf->type == type) {
368 if (conf->prefixlen == 255) {
369 for (res = conf->addrinfo; res; res = res->ai_next)
370 if ((a4 && res->ai_family == AF_INET &&
371 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
372 (sa6 && res->ai_family == AF_INET6 &&
373 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
376 res = conf->addrinfo;
378 ((a4 && res->ai_family == AF_INET &&
379 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
380 (sa6 && res->ai_family == AF_INET6 &&
381 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
388 /* returns next config with matching address, or NULL */
389 struct clsrvconf *find_conf(char type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
390 struct sockaddr_in6 *sa6 = NULL;
391 struct in_addr *a4 = NULL;
392 struct addrinfo *res;
393 struct list_node *entry;
394 struct clsrvconf *conf;
396 if (addr->sa_family == AF_INET6) {
397 sa6 = (struct sockaddr_in6 *)addr;
398 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
399 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
403 a4 = &((struct sockaddr_in *)addr)->sin_addr;
405 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
406 conf = (struct clsrvconf *)entry->data;
407 if (conf->type == type) {
408 if (conf->prefixlen == 255) {
409 for (res = conf->addrinfo; res; res = res->ai_next)
410 if ((a4 && res->ai_family == AF_INET &&
411 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
412 (sa6 && res->ai_family == AF_INET6 &&
413 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
419 res = conf->addrinfo;
421 ((a4 && res->ai_family == AF_INET &&
422 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
423 (sa6 && res->ai_family == AF_INET6 &&
424 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
435 struct replyq *newreplyq() {
436 struct replyq *replyq;
438 replyq = malloc(sizeof(struct replyq));
440 debugx(1, DBG_ERR, "malloc failed");
441 replyq->replies = list_create();
442 if (!replyq->replies)
443 debugx(1, DBG_ERR, "malloc failed");
444 pthread_mutex_init(&replyq->mutex, NULL);
445 pthread_cond_init(&replyq->cond, NULL);
449 struct client *addclient(struct clsrvconf *conf) {
450 struct client *new = malloc(sizeof(struct client));
453 debug(DBG_ERR, "malloc failed");
456 if (!conf->clients) {
457 conf->clients = list_create();
458 if (!conf->clients) {
459 debug(DBG_ERR, "malloc failed");
464 memset(new, 0, sizeof(struct client));
466 new->replyq = conf->type == 'T' ? newreplyq() : udp_server_replyq;
468 list_push(conf->clients, new);
472 void removeclient(struct client *client) {
473 struct list_node *entry;
475 if (!client || !client->conf->clients)
478 pthread_mutex_lock(&client->replyq->mutex);
479 for (entry = list_first(client->replyq->replies); entry; entry = list_next(entry))
480 free(((struct reply *)entry)->buf);
481 list_destroy(client->replyq->replies);
482 pthread_cond_destroy(&client->replyq->cond);
483 pthread_mutex_unlock(&client->replyq->mutex);
484 pthread_mutex_destroy(&client->replyq->mutex);
485 list_removedata(client->conf->clients, client);
489 void removeclientrqs(struct client *client) {
490 struct list_node *entry;
491 struct server *server;
495 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
496 server = ((struct clsrvconf *)entry->data)->servers;
497 pthread_mutex_lock(&server->newrq_mutex);
498 for (i = 0; i < MAX_REQUESTS; i++) {
499 rq = server->requests + i;
500 if (rq->from == client)
503 pthread_mutex_unlock(&server->newrq_mutex);
507 void freeserver(struct server *server, uint8_t destroymutex) {
511 free(server->requests);
512 free(server->dynamiclookuparg);
514 pthread_mutex_destroy(&server->lock);
515 pthread_cond_destroy(&server->newrq_cond);
516 pthread_mutex_destroy(&server->newrq_mutex);
521 int addserver(struct clsrvconf *conf) {
522 struct clsrvconf *res;
525 debug(DBG_ERR, "addserver: currently works with just one server per conf");
528 conf->servers = malloc(sizeof(struct server));
529 if (!conf->servers) {
530 debug(DBG_ERR, "malloc failed");
533 memset(conf->servers, 0, sizeof(struct server));
534 conf->servers->conf = conf;
536 if (conf->type == 'U') {
538 res = resolve_hostport('U', options.sourceudp, NULL);
539 srcudpres = res->addrinfo;
540 res->addrinfo = NULL;
543 switch (conf->addrinfo->ai_family) {
545 if (udp_client4_sock < 0) {
546 udp_client4_sock = bindtoaddr(srcudpres, AF_INET, 0, 1);
547 if (udp_client4_sock < 0)
548 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
550 conf->servers->sock = udp_client4_sock;
553 if (udp_client6_sock < 0) {
554 udp_client6_sock = bindtoaddr(srcudpres, AF_INET6, 0, 1);
555 if (udp_client6_sock < 0)
556 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
558 conf->servers->sock = udp_client6_sock;
561 debugx(1, DBG_ERR, "addserver: unsupported address family");
566 res = resolve_hostport('T', options.sourcetcp, NULL);
567 srctcpres = res->addrinfo;
568 res->addrinfo = NULL;
571 conf->servers->sock = -1;
574 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
575 if (!conf->servers->requests) {
576 debug(DBG_ERR, "malloc failed");
579 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
580 debug(DBG_ERR, "mutex init failed");
583 conf->servers->newrq = 0;
584 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
585 debug(DBG_ERR, "mutex init failed");
586 pthread_mutex_destroy(&conf->servers->lock);
589 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
590 debug(DBG_ERR, "mutex init failed");
591 pthread_mutex_destroy(&conf->servers->newrq_mutex);
592 pthread_mutex_destroy(&conf->servers->lock);
599 freeserver(conf->servers, 0);
600 conf->servers = NULL;
604 /* exactly one of client and server must be non-NULL */
605 /* should probably take peer list (client(s) or server(s)) as argument instead */
606 /* if *peer == NULL we return who we received from, else require it to be from peer */
607 /* return from in sa if not NULL */
608 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
610 unsigned char buf[65536], *rad;
611 struct sockaddr_storage from;
612 socklen_t fromlen = sizeof(from);
614 struct list_node *node;
617 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
619 debug(DBG_WARN, "radudpget: recv failed");
622 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
625 debug(DBG_WARN, "radudpget: packet too small");
631 debug(DBG_WARN, "radudpget: length too small");
636 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
640 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
644 p = checkconfaddr('U', (struct sockaddr *)&from, (*client)->conf);
646 p = find_conf('U', (struct sockaddr *)&from, clconfs, NULL);
649 p = checkconfaddr('U', (struct sockaddr *)&from, (*server)->conf);
651 p = find_conf('U', (struct sockaddr *)&from, srvconfs, NULL);
654 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
660 debug(DBG_ERR, "radudpget: malloc failed");
664 if (client && !*client) {
665 node = list_first(p->clients);
666 *client = node ? (struct client *)node->data : addclient(p);
671 } else if (server && !*server)
672 *server = p->servers;
676 memcpy(rad, buf, len);
682 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
683 int loc, i, l, n, r = 0;
686 STACK_OF(GENERAL_NAME) *alt;
689 debug(DBG_DBG, "subjectaltnameaddr");
691 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
695 ex = X509_get_ext(cert, loc);
696 alt = X509V3_EXT_d2i(ex);
700 n = sk_GENERAL_NAME_num(alt);
701 for (i = 0; i < n; i++) {
702 gn = sk_GENERAL_NAME_value(alt, i);
703 if (gn->type != GEN_IPADD)
706 v = (char *)ASN1_STRING_data(gn->d.ia5);
707 l = ASN1_STRING_length(gn->d.ia5);
708 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
709 && !memcmp(v, &addr, l)) {
714 GENERAL_NAMES_free(alt);
718 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
725 nm = X509_get_subject_name(cert);
728 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
731 e = X509_NAME_get_entry(nm, loc);
732 t = X509_NAME_ENTRY_get_data(e);
733 v = (char *) ASN1_STRING_data(t);
734 l = ASN1_STRING_length(t);
738 if (l == strlen(exact) && !strncasecmp(exact, v, l))
741 s = stringcopy((char *)v, l);
743 debug(DBG_ERR, "malloc failed");
746 if (regexec(regex, s, 0, NULL, 0)) {
757 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
758 int loc, i, l, n, r = 0;
761 STACK_OF(GENERAL_NAME) *alt;
764 debug(DBG_DBG, "subjectaltnameregexp");
766 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
770 ex = X509_get_ext(cert, loc);
771 alt = X509V3_EXT_d2i(ex);
775 n = sk_GENERAL_NAME_num(alt);
776 for (i = 0; i < n; i++) {
777 gn = sk_GENERAL_NAME_value(alt, i);
778 if (gn->type != type)
781 v = (char *)ASN1_STRING_data(gn->d.ia5);
782 l = ASN1_STRING_length(gn->d.ia5);
786 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
789 if (memcmp(v, exact, l))
792 s = stringcopy((char *)v, l);
794 debug(DBG_ERR, "malloc failed");
797 if (regexec(regex, s, 0, NULL, 0)) {
806 GENERAL_NAMES_free(alt);
810 X509 *verifytlscert(SSL *ssl) {
814 if (SSL_get_verify_result(ssl) != X509_V_OK) {
815 debug(DBG_ERR, "verifytlscert: basic validation failed");
816 while ((error = ERR_get_error()))
817 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
821 cert = SSL_get_peer_certificate(ssl);
823 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
827 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
829 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
830 struct in6_addr addr;
832 if (conf->certnamecheck && conf->prefixlen == 255) {
833 if (inet_pton(AF_INET, conf->host, &addr))
835 else if (inet_pton(AF_INET6, conf->host, &addr))
838 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
841 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
844 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
846 if (!cnregexp(cert, conf->host, NULL)) {
847 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
850 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
853 if (conf->certcnregex) {
854 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
855 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
858 debug(DBG_DBG, "verifyconfcert: CN matching regex");
860 if (conf->certuriregex) {
861 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
862 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
865 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
870 void tlsconnect(struct server *server, struct timeval *when, char *text) {
875 debug(DBG_DBG, "tlsconnect called from %s", text);
876 pthread_mutex_lock(&server->lock);
877 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
878 /* already reconnected, nothing to do */
879 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
880 pthread_mutex_unlock(&server->lock);
884 debug(DBG_DBG, "tlsconnect %s", text);
887 gettimeofday(&now, NULL);
888 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
889 if (server->connectionok) {
890 server->connectionok = 0;
892 } else if (elapsed < 1)
894 else if (elapsed < 60) {
895 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
897 } else if (elapsed < 100000) {
898 debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
901 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
902 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
903 if (server->sock >= 0)
905 if ((server->sock = connecttcp(server->conf->addrinfo)) < 0) {
906 debug(DBG_ERR, "tlsconnect: connecttcp failed");
910 SSL_free(server->ssl);
911 server->ssl = SSL_new(server->conf->ssl_ctx);
912 SSL_set_fd(server->ssl, server->sock);
913 if (SSL_connect(server->ssl) <= 0)
915 cert = verifytlscert(server->ssl);
918 if (verifyconfcert(cert, server->conf)) {
924 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
925 gettimeofday(&server->lastconnecttry, NULL);
926 pthread_mutex_unlock(&server->lock);
929 unsigned char *radtlsget(SSL *ssl) {
931 unsigned char buf[4], *rad;
934 for (total = 0; total < 4; total += cnt) {
935 cnt = SSL_read(ssl, buf + total, 4 - total);
937 debug(DBG_ERR, "radtlsget: connection lost");
938 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
939 /* remote end sent close_notify, send one back */
949 debug(DBG_ERR, "radtlsget: malloc failed");
954 for (; total < len; total += cnt) {
955 cnt = SSL_read(ssl, rad + total, len - total);
957 debug(DBG_ERR, "radtlsget: connection lost");
958 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
959 /* remote end sent close_notify, send one back */
971 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
974 debug(DBG_DBG, "radtlsget: got %d bytes", total);
978 int clientradputudp(struct server *server, unsigned char *rad) {
980 struct sockaddr_storage sa;
981 struct sockaddr *sap;
982 struct clsrvconf *conf = server->conf;
983 in_port_t *port = NULL;
987 if (*rad == RAD_Accounting_Request) {
988 sap = (struct sockaddr *)&sa;
989 memcpy(sap, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen);
991 sap = conf->addrinfo->ai_addr;
993 switch (sap->sa_family) {
995 port = &((struct sockaddr_in *)sap)->sin_port;
998 port = &((struct sockaddr_in6 *)sap)->sin6_port;
1004 if (*rad == RAD_Accounting_Request)
1005 *port = htons(ntohs(*port) + 1);
1007 if (sendto(server->sock, rad, len, 0, sap, conf->addrinfo->ai_addrlen) >= 0) {
1008 debug(DBG_DBG, "clienradputudp: sent UDP of length %d to %s port %d", len, conf->host, ntohs(*port));
1012 debug(DBG_WARN, "clientradputudp: send failed");
1016 int clientradputtls(struct server *server, unsigned char *rad) {
1019 unsigned long error;
1020 struct timeval lastconnecttry;
1021 struct clsrvconf *conf = server->conf;
1024 lastconnecttry = server->lastconnecttry;
1025 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
1026 while ((error = ERR_get_error()))
1027 debug(DBG_ERR, "clientradputtls: TLS: %s", ERR_error_string(error, NULL));
1028 tlsconnect(server, &lastconnecttry, "clientradputtls");
1029 lastconnecttry = server->lastconnecttry;
1032 server->connectionok = 1;
1033 debug(DBG_DBG, "clientradputtls: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
1037 int clientradput(struct server *server, unsigned char *rad) {
1038 switch (server->conf->type) {
1040 return clientradputudp(server, rad);
1042 return clientradputtls(server, rad);
1047 int radsign(unsigned char *rad, unsigned char *sec) {
1048 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1049 static unsigned char first = 1;
1050 static EVP_MD_CTX mdctx;
1051 unsigned int md_len;
1054 pthread_mutex_lock(&lock);
1056 EVP_MD_CTX_init(&mdctx);
1060 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1061 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
1062 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1063 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
1065 pthread_mutex_unlock(&lock);
1069 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
1070 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1071 static unsigned char first = 1;
1072 static EVP_MD_CTX mdctx;
1073 unsigned char hash[EVP_MAX_MD_SIZE];
1077 pthread_mutex_lock(&lock);
1079 EVP_MD_CTX_init(&mdctx);
1085 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1086 EVP_DigestUpdate(&mdctx, rad, 4) &&
1087 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
1088 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
1089 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1090 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
1092 !memcmp(hash, rad + 4, 16));
1093 pthread_mutex_unlock(&lock);
1097 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
1098 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1099 static unsigned char first = 1;
1100 static HMAC_CTX hmacctx;
1101 unsigned int md_len;
1102 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
1104 pthread_mutex_lock(&lock);
1106 HMAC_CTX_init(&hmacctx);
1110 memcpy(auth, authattr, 16);
1111 memset(authattr, 0, 16);
1113 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1114 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1115 HMAC_Final(&hmacctx, hash, &md_len);
1116 memcpy(authattr, auth, 16);
1118 debug(DBG_WARN, "message auth computation failed");
1119 pthread_mutex_unlock(&lock);
1123 if (memcmp(auth, hash, 16)) {
1124 debug(DBG_WARN, "message authenticator, wrong value");
1125 pthread_mutex_unlock(&lock);
1129 pthread_mutex_unlock(&lock);
1133 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
1134 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1135 static unsigned char first = 1;
1136 static HMAC_CTX hmacctx;
1137 unsigned int md_len;
1142 pthread_mutex_lock(&lock);
1144 HMAC_CTX_init(&hmacctx);
1148 memset(authattrval, 0, 16);
1150 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1151 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1152 HMAC_Final(&hmacctx, authattrval, &md_len);
1154 debug(DBG_WARN, "message auth computation failed");
1155 pthread_mutex_unlock(&lock);
1159 pthread_mutex_unlock(&lock);
1163 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
1164 while (length > 1) {
1165 if (ATTRTYPE(attrs) == type)
1167 length -= ATTRLEN(attrs);
1168 attrs += ATTRLEN(attrs);
1173 void freerqdata(struct request *rq) {
1174 if (rq->origusername)
1175 free(rq->origusername);
1180 void sendrq(struct server *to, struct request *rq) {
1184 pthread_mutex_lock(&to->newrq_mutex);
1185 /* might simplify if only try nextid, might be ok */
1186 for (i = to->nextid; i < MAX_REQUESTS; i++)
1187 if (!to->requests[i].buf)
1189 if (i == MAX_REQUESTS) {
1190 for (i = 0; i < to->nextid; i++)
1191 if (!to->requests[i].buf)
1193 if (i == to->nextid) {
1194 debug(DBG_WARN, "No room in queue, dropping request");
1196 pthread_mutex_unlock(&to->newrq_mutex);
1201 rq->buf[1] = (char)i;
1203 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1204 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1206 pthread_mutex_unlock(&to->newrq_mutex);
1210 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1211 to->requests[i] = *rq;
1216 debug(DBG_DBG, "signalling client writer");
1217 pthread_cond_signal(&to->newrq_cond);
1219 pthread_mutex_unlock(&to->newrq_mutex);
1222 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
1223 struct reply *reply;
1226 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1228 debug(DBG_WARN, "sendreply: failed to sign message");
1232 reply = malloc(sizeof(struct reply));
1235 debug(DBG_ERR, "sendreply: malloc failed");
1238 memset(reply, 0, sizeof(struct reply));
1241 reply->tosa = *tosa;
1243 pthread_mutex_lock(&to->replyq->mutex);
1245 first = list_first(to->replyq->replies) == NULL;
1247 if (!list_push(to->replyq->replies, reply)) {
1248 pthread_mutex_unlock(&to->replyq->mutex);
1251 debug(DBG_ERR, "sendreply: malloc failed");
1256 debug(DBG_DBG, "signalling server writer");
1257 pthread_cond_signal(&to->replyq->cond);
1259 pthread_mutex_unlock(&to->replyq->mutex);
1262 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1263 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1264 static unsigned char first = 1;
1265 static EVP_MD_CTX mdctx;
1266 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1267 unsigned int md_len;
1268 uint8_t i, offset = 0, out[128];
1270 pthread_mutex_lock(&lock);
1272 EVP_MD_CTX_init(&mdctx);
1278 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1279 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1280 !EVP_DigestUpdate(&mdctx, input, 16) ||
1281 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1283 pthread_mutex_unlock(&lock);
1286 for (i = 0; i < 16; i++)
1287 out[offset + i] = hash[i] ^ in[offset + i];
1288 input = out + offset - 16;
1293 memcpy(in, out, len);
1294 pthread_mutex_unlock(&lock);
1298 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1299 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1300 static unsigned char first = 1;
1301 static EVP_MD_CTX mdctx;
1302 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1303 unsigned int md_len;
1304 uint8_t i, offset = 0, out[128];
1306 pthread_mutex_lock(&lock);
1308 EVP_MD_CTX_init(&mdctx);
1314 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1315 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1316 !EVP_DigestUpdate(&mdctx, input, 16) ||
1317 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1319 pthread_mutex_unlock(&lock);
1322 for (i = 0; i < 16; i++)
1323 out[offset + i] = hash[i] ^ in[offset + i];
1324 input = in + offset;
1329 memcpy(in, out, len);
1330 pthread_mutex_unlock(&lock);
1334 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1335 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1336 static unsigned char first = 1;
1337 static EVP_MD_CTX mdctx;
1338 unsigned char hash[EVP_MAX_MD_SIZE];
1339 unsigned int md_len;
1342 pthread_mutex_lock(&lock);
1344 EVP_MD_CTX_init(&mdctx);
1349 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1350 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1351 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1354 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1355 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1356 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1357 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1358 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1359 pthread_mutex_unlock(&lock);
1364 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1367 for (i = 0; i < 16; i++)
1370 for (offset = 16; offset < len; offset += 16) {
1372 printf("text + offset - 16 c(%d): ", offset / 16);
1373 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1375 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1376 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1377 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1378 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1380 pthread_mutex_unlock(&lock);
1384 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1387 for (i = 0; i < 16; i++)
1388 text[offset + i] ^= hash[i];
1392 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1395 pthread_mutex_unlock(&lock);
1399 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1400 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1401 static unsigned char first = 1;
1402 static EVP_MD_CTX mdctx;
1403 unsigned char hash[EVP_MAX_MD_SIZE];
1404 unsigned int md_len;
1408 pthread_mutex_lock(&lock);
1410 EVP_MD_CTX_init(&mdctx);
1415 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1416 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1417 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1420 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1421 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1422 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1423 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1424 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1425 pthread_mutex_unlock(&lock);
1430 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1433 for (i = 0; i < 16; i++)
1434 plain[i] = text[i] ^ hash[i];
1436 for (offset = 16; offset < len; offset += 16) {
1438 printf("text + offset - 16 c(%d): ", offset / 16);
1439 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1441 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1442 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1443 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1444 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1446 pthread_mutex_unlock(&lock);
1450 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1453 for (i = 0; i < 16; i++)
1454 plain[offset + i] = text[offset + i] ^ hash[i];
1457 memcpy(text, plain, len);
1459 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1462 pthread_mutex_unlock(&lock);
1466 struct realm *id2realm(struct list *realmlist, char *id) {
1467 struct list_node *entry;
1468 struct realm *realm, *subrealm = NULL;
1470 /* need to do locking for subrealms and check subrealm timers */
1471 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1472 realm = (struct realm *)entry->data;
1473 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1474 pthread_mutex_lock(&realm->subrealms_mutex);
1475 if (realm->subrealms)
1476 subrealm = id2realm(realm->subrealms, id);
1477 pthread_mutex_unlock(&realm->subrealms_mutex);
1478 return subrealm ? subrealm : realm;
1484 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1485 struct request *rq = to->requests, *end;
1487 pthread_mutex_lock(&to->newrq_mutex);
1488 for (end = rq + MAX_REQUESTS; rq < end; rq++)
1489 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1491 pthread_mutex_unlock(&to->newrq_mutex);
1496 int attrvalidate(unsigned char *attrs, int length) {
1497 while (length > 1) {
1498 if (ATTRLEN(attrs) < 2) {
1499 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1502 length -= ATTRLEN(attrs);
1504 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1507 attrs += ATTRLEN(attrs);
1510 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1514 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1515 if (len < 16 || len > 128 || len % 16) {
1516 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1520 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1521 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1525 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1527 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1528 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1534 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1537 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1538 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1541 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1542 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1548 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1549 char *oldsecret, char *newsecret) {
1550 unsigned char *attr;
1552 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1553 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1554 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1560 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1564 for (; attrs[0]; attrs += 2)
1565 if (attrs[0] == vendor && attrs[1] == subattr)
1570 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1571 uint8_t alen, sublen, rmlen = 0;
1572 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1575 if (!removevendorattrs)
1578 while (*removevendorattrs && *removevendorattrs != vendor)
1579 removevendorattrs += 2;
1580 if (!*removevendorattrs)
1583 alen = ATTRLEN(attrs);
1585 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1586 /* remove entire vendor attribute */
1587 memmove(attrs, attrs + alen, length - alen);
1592 subattrs = ATTRVAL(attrs) + 4;
1594 if (!attrvalidate(subattrs, sublen)) {
1595 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1600 while (sublen > 1) {
1601 alen = ATTRLEN(subattrs);
1604 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1605 memmove(subattrs, subattrs + alen, length);
1611 ATTRLEN(attrs) -= rmlen;
1615 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1616 uint8_t *attrs, alen;
1617 uint16_t len, rmlen = 0;
1619 if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1622 len = RADLEN(buf) - 20;
1625 alen = ATTRLEN(attrs);
1627 if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1628 memmove(attrs, attrs + alen, len);
1630 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1631 rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1636 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1639 /* returns a pointer to the resized attribute value */
1640 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1641 uint8_t *attrs, *attr, vallen;
1645 len = RADLEN(*buf) - 20;
1648 attr = attrget(attrs, len, type);
1652 vallen = ATTRVALLEN(attr);
1653 if (vallen == newvallen)
1656 len += newvallen - vallen;
1657 if (newvallen > vallen) {
1658 new = realloc(*buf, len + 20);
1660 debug(DBG_ERR, "resizeattr: malloc failed");
1669 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1670 attr[1] = newvallen + 2;
1671 ((uint16_t *)*buf)[1] = htons(len + 20);
1675 int rewriteusername(struct request *rq, char *in) {
1676 size_t nmatch = 10, reslen = 0, start = 0;
1677 regmatch_t pmatch[10], *pfield;
1679 unsigned char *result;
1680 char *out = rq->from->conf->rewriteattrreplacement;
1682 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1683 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1687 rq->origusername = stringcopy(in, 0);
1688 if (!rq->origusername)
1691 for (i = start; out[i]; i++) {
1692 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1693 pfield = &pmatch[out[i + 1] - '0'];
1694 if (pfield->rm_so >= 0) {
1695 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1701 reslen += i - start;
1703 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1709 for (i = start; out[i]; i++) {
1710 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1711 pfield = &pmatch[out[i + 1] - '0'];
1712 if (pfield->rm_so >= 0) {
1713 memcpy(result + reslen, out + start, i - start);
1714 reslen += i - start;
1715 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1716 reslen += pfield->rm_eo - pfield->rm_so;
1723 memcpy(result + reslen, out + start, i - start);
1724 reslen += i - start;
1725 memcpy(in, result, reslen);
1730 const char *radmsgtype2string(uint8_t code) {
1731 static const char *rad_msg_names[] = {
1732 "", "Access-Request", "Access-Accept", "Access-Reject",
1733 "Accounting-Request", "Accounting-Response", "", "",
1734 "", "", "", "Access-Challenge",
1735 "Status-Server", "Status-Client"
1737 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1740 void acclog(unsigned char *attrs, int length, char *host) {
1741 unsigned char *attr;
1744 attr = attrget(attrs, length, RAD_Attr_User_Name);
1746 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1749 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1750 username[ATTRVALLEN(attr)] = '\0';
1751 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1754 void respondaccounting(struct request *rq) {
1755 unsigned char *resp;
1759 debug(DBG_ERR, "respondstatusserver: malloc failed");
1762 memcpy(resp, rq->buf, 20);
1763 resp[0] = RAD_Accounting_Response;
1766 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1767 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1770 void respondstatusserver(struct request *rq) {
1771 unsigned char *resp;
1775 debug(DBG_ERR, "respondstatusserver: malloc failed");
1778 memcpy(resp, rq->buf, 20);
1779 resp[0] = RAD_Access_Accept;
1782 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1783 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1786 void respondreject(struct request *rq, char *message) {
1787 unsigned char *resp;
1790 if (message && *message)
1791 len += 2 + strlen(message);
1795 debug(DBG_ERR, "respondreject: malloc failed");
1798 memcpy(resp, rq->buf, 20);
1799 resp[0] = RAD_Access_Reject;
1800 *(uint16_t *)(resp + 2) = htons(len);
1801 if (message && *message) {
1802 resp[20] = RAD_Attr_Reply_Message;
1803 resp[21] = len - 20;
1804 memcpy(resp + 22, message, len - 22);
1806 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1809 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1810 struct list_node *entry;
1811 struct clsrvconf *server, *best = NULL, *first = NULL;
1813 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1814 server = (struct clsrvconf *)entry->data;
1815 if (!server->servers)
1819 if (!server->servers->connectionok)
1821 if (!server->servers->loststatsrv)
1827 if (server->servers->loststatsrv < best->servers->loststatsrv)
1830 return best ? best : first;
1833 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
1834 struct clsrvconf *srvconf;
1836 *realm = id2realm(realms, id);
1839 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1840 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1841 if (!acc && !srvconf->servers)
1842 adddynamicrealmserver(*realm, srvconf, id);
1843 return srvconf->servers;
1846 void radsrv(struct request *rq) {
1847 uint8_t code, id, *auth, *attrs, *attr;
1849 struct server *to = NULL;
1851 unsigned char newauth[16];
1852 struct realm *realm = NULL;
1854 code = *(uint8_t *)rq->buf;
1855 id = *(uint8_t *)(rq->buf + 1);
1856 len = RADLEN(rq->buf);
1857 auth = (uint8_t *)(rq->buf + 4);
1859 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1861 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1862 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1867 attrs = rq->buf + 20;
1869 if (!attrvalidate(attrs, len)) {
1870 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1874 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1875 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
1876 debug(DBG_WARN, "radsrv: message authentication failed");
1880 if (code == RAD_Status_Server) {
1881 respondstatusserver(rq);
1885 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1887 if (rq->from->conf->rewrite) {
1888 dorewrite(rq->buf, rq->from->conf->rewrite);
1889 len = RADLEN(rq->buf) - 20;
1892 attr = attrget(attrs, len, RAD_Attr_User_Name);
1894 if (code == RAD_Accounting_Request) {
1895 acclog(attrs, len, rq->from->conf->host);
1896 respondaccounting(rq);
1898 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1901 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1902 username[ATTRVALLEN(attr)] = '\0';
1904 if (rq->from->conf->rewriteattrregex) {
1905 if (!rewriteusername(rq, username)) {
1906 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1909 len = RADLEN(rq->buf) - 20;
1910 auth = (uint8_t *)(rq->buf + 4);
1911 attrs = rq->buf + 20;
1914 if (rq->origusername)
1915 debug(DBG_DBG, "%s with username: %s (originally %s)", radmsgtype2string(code), username, rq->origusername);
1917 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), username);
1919 to = findserver(&realm, username, code == RAD_Accounting_Request);
1921 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1925 if (realm->message && code == RAD_Access_Request) {
1926 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, username);
1927 respondreject(rq, realm->message);
1932 if (rqinqueue(to, rq->from, id, code)) {
1933 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
1934 radmsgtype2string(code), rq->from->conf->host, id);
1938 if (!RAND_bytes(newauth, 16)) {
1939 debug(DBG_WARN, "radsrv: failed to generate random auth");
1944 printfchars(NULL, "auth", "%02x ", auth, 16);
1947 attr = attrget(attrs, len, RAD_Attr_User_Password);
1949 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1950 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
1954 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1956 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1957 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
1962 memcpy(rq->origauth, auth, 16);
1963 memcpy(auth, newauth, 16);
1971 int replyh(struct server *server, unsigned char *buf) {
1972 struct client *from;
1975 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
1976 struct sockaddr_storage fromsa;
1979 server->connectionok = 1;
1980 server->loststatsrv = 0;
1982 i = buf[1]; /* i is the id */
1984 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
1985 && *buf != RAD_Accounting_Response) {
1986 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
1989 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
1991 rq = server->requests + i;
1993 pthread_mutex_lock(&server->newrq_mutex);
1994 if (!rq->buf || !rq->tries) {
1995 pthread_mutex_unlock(&server->newrq_mutex);
1996 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
2001 pthread_mutex_unlock(&server->newrq_mutex);
2002 debug(DBG_INFO, "replyh: already received, ignoring reply");
2006 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
2007 pthread_mutex_unlock(&server->newrq_mutex);
2008 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
2012 len = RADLEN(buf) - 20;
2015 if (!attrvalidate(attrs, len)) {
2016 pthread_mutex_unlock(&server->newrq_mutex);
2017 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
2021 /* Message Authenticator */
2022 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2024 if (ATTRVALLEN(messageauth) != 16) {
2025 pthread_mutex_unlock(&server->newrq_mutex);
2026 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
2029 memcpy(tmp, buf + 4, 16);
2030 memcpy(buf + 4, rq->buf + 4, 16);
2031 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
2032 pthread_mutex_unlock(&server->newrq_mutex);
2033 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
2036 memcpy(buf + 4, tmp, 16);
2037 debug(DBG_DBG, "replyh: message auth ok");
2040 if (*rq->buf == RAD_Status_Server) {
2042 pthread_mutex_unlock(&server->newrq_mutex);
2043 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2049 pthread_mutex_unlock(&server->newrq_mutex);
2050 debug(DBG_INFO, "replyh: client gone, ignoring reply");
2054 if (server->conf->rewrite) {
2055 dorewrite(buf, server->conf->rewrite);
2056 len = RADLEN(buf) - 20;
2060 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2061 if (ATTRVALLEN(attr) <= 4)
2064 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
2067 sublen = ATTRVALLEN(attr) - 4;
2068 subattrs = ATTRVAL(attr) + 4;
2069 if (!attrvalidate(subattrs, sublen) ||
2070 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2071 rq, server->conf->secret, from->conf->secret) ||
2072 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2073 rq, server->conf->secret, from->conf->secret))
2077 pthread_mutex_unlock(&server->newrq_mutex);
2078 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2082 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2083 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2085 memcpy(tmp, ATTRVAL(attr), ATTRVALLEN(attr));
2086 tmp[ATTRVALLEN(attr)] = '\0';
2087 if (rq->origusername)
2088 debug(DBG_INFO, "%s for %s (originally %s) from %s", radmsgtype2string(*buf), tmp,
2089 rq->origusername, server->conf->host);
2091 debug(DBG_INFO, "%s for %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2095 buf[1] = (char)rq->origid;
2096 memcpy(buf + 4, rq->origauth, 16);
2098 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2101 if (rq->origusername) {
2102 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2104 pthread_mutex_unlock(&server->newrq_mutex);
2105 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2108 memcpy(username, rq->origusername, strlen(rq->origusername));
2109 len = RADLEN(buf) - 20;
2112 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2116 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2117 pthread_mutex_unlock(&server->newrq_mutex);
2118 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2121 debug(DBG_DBG, "replyh: computed messageauthattr");
2124 if (from->conf->type == 'U')
2125 fromsa = rq->fromsa;
2126 /* once we set received = 1, rq may be reused */
2129 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2130 sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
2131 pthread_mutex_unlock(&server->newrq_mutex);
2135 void *udpclientrd(void *arg) {
2136 struct server *server;
2138 int *s = (int *)arg;
2142 buf = radudpget(*s, NULL, &server, NULL);
2143 if (!replyh(server, buf))
2148 void *tlsclientrd(void *arg) {
2149 struct server *server = (struct server *)arg;
2151 struct timeval lastconnecttry;
2154 /* yes, lastconnecttry is really necessary */
2155 lastconnecttry = server->lastconnecttry;
2156 buf = radtlsget(server->ssl);
2158 tlsconnect(server, &lastconnecttry, "clientrd");
2162 if (!replyh(server, buf))
2167 /* code for removing state not finished */
2168 void *clientwr(void *arg) {
2169 struct server *server = (struct server *)arg;
2171 pthread_t tlsclientrdth;
2174 struct timeval now, lastsend;
2175 struct timespec timeout;
2176 struct request statsrvrq;
2177 unsigned char statsrvbuf[38];
2178 struct clsrvconf *conf;
2180 conf = server->conf;
2182 if (server->dynamiclookuparg) {
2183 dynamicconfig(server);
2184 conf = server->conf;
2189 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2190 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2194 memset(&timeout, 0, sizeof(struct timespec));
2196 if (conf->statusserver) {
2197 memset(&statsrvrq, 0, sizeof(struct request));
2198 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2199 statsrvbuf[0] = RAD_Status_Server;
2201 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2202 statsrvbuf[21] = 18;
2203 gettimeofday(&lastsend, NULL);
2206 if (conf->type == 'U') {
2207 server->connectionok = 1;
2209 tlsconnect(server, NULL, "new client");
2210 server->connectionok = 1;
2211 if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server)) {
2212 debug(DBG_ERR, "clientwr: pthread_create failed");
2218 pthread_mutex_lock(&server->newrq_mutex);
2219 if (!server->newrq) {
2220 gettimeofday(&now, NULL);
2221 if (conf->statusserver) {
2222 /* random 0-7 seconds */
2223 RAND_bytes(&rnd, 1);
2225 if (!timeout.tv_sec || timeout.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
2226 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
2228 if (timeout.tv_sec) {
2229 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2230 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2233 debug(DBG_DBG, "clientwr: waiting for new request");
2234 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
2237 if (server->newrq) {
2238 debug(DBG_DBG, "clientwr: got new request");
2241 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2242 pthread_mutex_unlock(&server->newrq_mutex);
2244 for (i = 0; i < MAX_REQUESTS; i++) {
2245 pthread_mutex_lock(&server->newrq_mutex);
2246 while (i < MAX_REQUESTS && !server->requests[i].buf)
2248 if (i == MAX_REQUESTS) {
2249 pthread_mutex_unlock(&server->newrq_mutex);
2252 rq = server->requests + i;
2255 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2257 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2259 /* setting this to NULL means that it can be reused */
2262 pthread_mutex_unlock(&server->newrq_mutex);
2266 gettimeofday(&now, NULL);
2267 if (now.tv_sec < rq->expiry.tv_sec) {
2268 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2269 timeout.tv_sec = rq->expiry.tv_sec;
2270 pthread_mutex_unlock(&server->newrq_mutex);
2274 if (rq->tries == (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
2275 ? 1 : REQUEST_RETRIES)) {
2276 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2277 if (*rq->buf == RAD_Status_Server) {
2278 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2279 if (server->loststatsrv < 255)
2280 server->loststatsrv++;
2283 /* setting this to NULL means that it can be reused */
2285 pthread_mutex_unlock(&server->newrq_mutex);
2288 pthread_mutex_unlock(&server->newrq_mutex);
2290 rq->expiry.tv_sec = now.tv_sec +
2291 (*rq->buf == RAD_Status_Server || conf->type == 'T'
2292 ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
2293 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2294 timeout.tv_sec = rq->expiry.tv_sec;
2296 clientradput(server, server->requests[i].buf);
2297 gettimeofday(&lastsend, NULL);
2299 if (conf->statusserver) {
2300 gettimeofday(&now, NULL);
2301 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
2302 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2303 debug(DBG_WARN, "clientwr: failed to generate random auth");
2306 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2307 if (!statsrvrq.buf) {
2308 debug(DBG_ERR, "clientwr: malloc failed");
2311 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2312 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2313 lastsend.tv_sec = now.tv_sec;
2314 sendrq(server, &statsrvrq);
2319 /* this code needs more work */
2320 if (server->dynamiclookuparg) {
2321 /* remove subrealms using this server */
2322 /* need to free server->conf etc */
2326 if (conf->addrinfo) {
2327 freeaddrinfo(conf->addrinfo);
2328 conf->addrinfo = NULL;
2330 /* add this once realm removal in place
2332 server->conf = NULL;
2336 freeserver(server, 1);
2340 void *udpserverwr(void *arg) {
2341 struct replyq *replyq = udp_server_replyq;
2342 struct reply *reply;
2345 pthread_mutex_lock(&replyq->mutex);
2346 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2347 debug(DBG_DBG, "udp server writer, waiting for signal");
2348 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2349 debug(DBG_DBG, "udp server writer, got signal");
2351 pthread_mutex_unlock(&replyq->mutex);
2353 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
2354 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2355 debug(DBG_WARN, "sendudp: send failed");
2361 void *udpserverrd(void *arg) {
2363 pthread_t udpserverwrth;
2364 struct clsrvconf *listenres;
2366 listenres = resolve_hostport('U', options.listenudp, DEFAULT_UDP_PORT);
2367 if ((udp_server_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2368 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2370 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
2371 listenres->host ? listenres->host : "*", listenres->port);
2372 freeclsrvres(listenres);
2374 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
2375 debugx(1, DBG_ERR, "pthread_create failed");
2378 memset(&rq, 0, sizeof(struct request));
2379 rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
2384 void *udpaccserverrd(void *arg) {
2386 struct clsrvconf *listenres;
2388 listenres = resolve_hostport('U', options.listenaccudp, DEFAULT_UDP_PORT);
2389 if ((udp_accserver_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2390 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2392 debug(DBG_WARN, "udpaccserverrd: listening for UDP on %s:%s",
2393 listenres->host ? listenres->host : "*", listenres->port);
2394 freeclsrvres(listenres);
2397 memset(&rq, 0, sizeof(struct request));
2398 rq.buf = radudpget(udp_accserver_sock, &rq.from, NULL, &rq.fromsa);
2399 if (*(uint8_t *)rq.buf == RAD_Accounting_Request) {
2403 debug(DBG_INFO, "udpaccserverrd: got something other than accounting-request, ignoring");
2408 void *tlsserverwr(void *arg) {
2410 unsigned long error;
2411 struct client *client = (struct client *)arg;
2412 struct replyq *replyq;
2413 struct reply *reply;
2415 debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
2416 replyq = client->replyq;
2418 pthread_mutex_lock(&replyq->mutex);
2419 while (!list_first(replyq->replies)) {
2421 debug(DBG_DBG, "tls server writer, waiting for signal");
2422 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2423 debug(DBG_DBG, "tls server writer, got signal");
2426 /* ssl might have changed while waiting */
2427 pthread_mutex_unlock(&replyq->mutex);
2428 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2432 reply = (struct reply *)list_shift(replyq->replies);
2433 pthread_mutex_unlock(&replyq->mutex);
2434 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2436 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
2437 cnt, RADLEN(reply->buf));
2439 while ((error = ERR_get_error()))
2440 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2446 void tlsserverrd(struct client *client) {
2448 pthread_t tlsserverwrth;
2450 debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2452 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2453 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2458 memset(&rq, 0, sizeof(struct request));
2459 rq.buf = radtlsget(client->ssl);
2462 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2467 debug(DBG_ERR, "tlsserverrd: connection lost");
2468 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2470 pthread_mutex_lock(&client->replyq->mutex);
2471 pthread_cond_signal(&client->replyq->cond);
2472 pthread_mutex_unlock(&client->replyq->mutex);
2473 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2474 pthread_join(tlsserverwrth, NULL);
2475 removeclientrqs(client);
2476 debug(DBG_DBG, "tlsserverrd for %s exiting", client->conf->host);
2479 void *tlsservernew(void *arg) {
2481 struct sockaddr_storage from;
2482 size_t fromlen = sizeof(from);
2483 struct clsrvconf *conf;
2484 struct list_node *cur = NULL;
2487 unsigned long error;
2488 struct client *client;
2491 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
2492 debug(DBG_DBG, "tlsserverrd: getpeername failed, exiting");
2495 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2497 conf = find_conf('T', (struct sockaddr *)&from, clconfs, &cur);
2499 ssl = SSL_new(conf->ssl_ctx);
2502 if (SSL_accept(ssl) <= 0) {
2503 while ((error = ERR_get_error()))
2504 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2505 debug(DBG_ERR, "SSL_accept failed");
2508 cert = verifytlscert(ssl);
2514 if (verifyconfcert(cert, conf)) {
2516 client = addclient(conf);
2519 tlsserverrd(client);
2520 removeclient(client);
2522 debug(DBG_WARN, "Failed to create new client instance");
2525 conf = find_conf('T', (struct sockaddr *)&from, clconfs, &cur);
2527 debug(DBG_WARN, "ignoring request, no matching TLS client");
2533 shutdown(s, SHUT_RDWR);
2539 pthread_t tlsserverth;
2541 struct sockaddr_storage from;
2542 size_t fromlen = sizeof(from);
2543 struct clsrvconf *listenres;
2545 listenres = resolve_hostport('T', options.listentcp, DEFAULT_TLS_PORT);
2546 if ((s = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2547 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
2549 debug(DBG_WARN, "listening for incoming TCP on %s:%s", listenres->host ? listenres->host : "*", listenres->port);
2550 freeclsrvres(listenres);
2554 snew = accept(s, (struct sockaddr *)&from, &fromlen);
2556 debug(DBG_WARN, "accept failed");
2559 if (pthread_create(&tlsserverth, NULL, tlsservernew, (void *)&snew)) {
2560 debug(DBG_ERR, "tlslistener: pthread_create failed");
2561 shutdown(snew, SHUT_RDWR);
2565 pthread_detach(tlsserverth);
2570 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
2573 STACK_OF(X509_NAME) *calist;
2575 unsigned long error;
2577 if (!certfile || !certkeyfile)
2578 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2580 if (!cacertfile && !cacertpath)
2581 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2584 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2585 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2586 for (i = 0; i < CRYPTO_num_locks(); i++) {
2587 ssl_lock_count[i] = 0;
2588 pthread_mutex_init(&ssl_locks[i], NULL);
2590 CRYPTO_set_id_callback(ssl_thread_id);
2591 CRYPTO_set_locking_callback(ssl_locking_callback);
2593 SSL_load_error_strings();
2596 while (!RAND_status()) {
2597 time_t t = time(NULL);
2598 pid_t pid = getpid();
2599 RAND_seed((unsigned char *)&t, sizeof(time_t));
2600 RAND_seed((unsigned char *)&pid, sizeof(pid));
2603 ctx = SSL_CTX_new(TLSv1_method());
2605 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2606 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2608 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2609 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2610 !SSL_CTX_check_private_key(ctx) ||
2611 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2612 while ((error = ERR_get_error()))
2613 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2614 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2617 calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
2618 if (!cacertfile || calist) {
2621 calist = sk_X509_NAME_new_null();
2622 if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
2623 sk_X509_NAME_free(calist);
2629 while ((error = ERR_get_error()))
2630 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2631 debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
2633 SSL_CTX_set_client_CA_list(ctx, calist);
2635 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2636 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2638 new = malloc(sizeof(struct tls));
2639 if (!new || !list_push(tlsconfs, new))
2640 debugx(1, DBG_ERR, "malloc failed");
2642 memset(new, 0, sizeof(struct tls));
2643 new->name = stringcopy(value, 0);
2645 debugx(1, DBG_ERR, "malloc failed");
2648 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2652 struct list_node *entry;
2655 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2656 t = (struct tls *)entry->data;
2660 SSL_CTX_free(t->ctx);
2662 list_destroy(tlsconfs);
2666 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2667 struct list_node *entry;
2668 struct tls *t, *t1 = NULL, *t2 = NULL;
2670 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2671 t = (struct tls *)entry->data;
2672 if (!strcasecmp(t->name, alt1)) {
2676 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2687 struct list *addsrvconfs(char *value, char **names) {
2688 struct list *conflist;
2690 struct list_node *entry;
2691 struct clsrvconf *conf;
2693 if (!names || !*names)
2696 conflist = list_create();
2698 debug(DBG_ERR, "malloc failed");
2702 for (n = 0; names[n]; n++) {
2703 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2704 conf = (struct clsrvconf *)entry->data;
2705 if (!strcasecmp(names[n], conf->name))
2709 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2710 list_destroy(conflist);
2713 if (!list_push(conflist, conf)) {
2714 debug(DBG_ERR, "malloc failed");
2715 list_destroy(conflist);
2718 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2723 void freerealm(struct realm *realm) {
2727 if (realm->srvconfs) {
2728 /* emptying list without freeing data */
2729 while (list_shift(realm->srvconfs));
2730 list_destroy(realm->srvconfs);
2732 if (realm->accsrvconfs) {
2733 /* emptying list without freeing data */
2734 while (list_shift(realm->accsrvconfs));
2735 list_destroy(realm->accsrvconfs);
2740 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message) {
2742 struct realm *realm;
2743 char *s, *regex = NULL;
2745 if (*value == '/') {
2746 /* regexp, remove optional trailing / if present */
2747 if (value[strlen(value) - 1] == '/')
2748 value[strlen(value) - 1] = '\0';
2750 /* not a regexp, let us make it one */
2751 if (*value == '*' && !value[1])
2752 regex = stringcopy(".*", 0);
2754 for (n = 0, s = value; *s;)
2757 regex = malloc(strlen(value) + n + 3);
2760 for (n = 1, s = value; *s; s++) {
2770 debug(DBG_ERR, "malloc failed");
2773 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2776 realm = malloc(sizeof(struct realm));
2778 debug(DBG_ERR, "malloc failed");
2781 memset(realm, 0, sizeof(struct realm));
2782 realm->name = stringcopy(value, 0);
2784 debug(DBG_ERR, "malloc failed");
2787 if (message && strlen(message) > 253) {
2788 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2791 realm->message = message;
2793 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
2794 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2798 if (servers && *servers) {
2799 realm->srvconfs = addsrvconfs(value, servers);
2800 if (!realm->srvconfs)
2804 if (accservers && *accservers) {
2805 realm->accsrvconfs = addsrvconfs(value, accservers);
2806 if (!realm->accsrvconfs)
2810 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
2811 debug(DBG_ERR, "mutex init failed");
2815 if (!list_push(realmlist, realm)) {
2816 debug(DBG_ERR, "malloc failed");
2817 pthread_mutex_destroy(&realm->subrealms_mutex);
2821 debug(DBG_DBG, "addrealm: added realm %s", value);
2831 for (n = 0; servers[n]; n++)
2836 for (n = 0; accservers[n]; n++)
2837 free(accservers[n]);
2843 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2844 struct clsrvconf *srvconf;
2845 struct realm *newrealm = NULL;
2848 if (!conf->dynamiclookupcommand)
2851 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2852 realmname = strrchr(id, '@');
2859 pthread_mutex_lock(&realm->subrealms_mutex);
2860 /* exit if we now already got a matching subrealm */
2861 if (id2realm(realm->subrealms, id))
2863 srvconf = malloc(sizeof(struct clsrvconf));
2865 debug(DBG_ERR, "malloc failed");
2869 if (!addserver(srvconf))
2872 if (!realm->subrealms)
2873 realm->subrealms = list_create();
2874 if (!realm->subrealms)
2876 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL);
2880 /* add server and accserver to newrealm */
2881 newrealm->srvconfs = list_create();
2882 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2883 debug(DBG_ERR, "malloc failed");
2886 newrealm->accsrvconfs = list_create();
2887 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2888 debug(DBG_ERR, "malloc failed");
2892 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2894 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2895 debug(DBG_ERR, "pthread_create failed");
2903 list_removedata(realm->subrealms, newrealm);
2904 freerealm(newrealm);
2906 freeserver(srvconf->servers, 1);
2908 debug(DBG_ERR, "failed to create dynamic server");
2911 pthread_mutex_unlock(&realm->subrealms_mutex);
2914 void dynconfserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2915 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *rewrite = NULL;
2916 struct clsrvconf *conf, *resconf;
2918 debug(DBG_DBG, "dynconfserver_cb called for %s", block);
2920 conf = malloc(sizeof(struct clsrvconf));
2922 debugx(1, DBG_ERR, "malloc failed");
2925 memset(conf, 0, sizeof(struct clsrvconf));
2926 conf->certnamecheck = 1;
2928 if (!getgenericconfig(cf, block,
2929 "type", CONF_STR, &type,
2930 "host", CONF_STR, &conf->host,
2931 "port", CONF_STR, &conf->port,
2932 "secret", CONF_STR, &conf->secret,
2933 "tls", CONF_STR, &tls,
2934 "MatchCertificateAttribute", CONF_STR, &matchcertattr,
2935 "rewrite", CONF_STR, &rewrite,
2936 "StatusServer", CONF_BLN, &conf->statusserver,
2937 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2938 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
2941 debugx(1, DBG_ERR, "configuration error");
2943 conf->name = stringcopy(val, 0);
2945 conf->host = stringcopy(val, 0);
2946 /* need to copy other params */
2947 /* any params used from template needs to be duplicated */
2948 resconf = (struct clsrvconf *)arg;
2949 resconf->name = conf->name;
2951 resconf->host = conf->host;
2953 /* free conf here */
2957 void dynamicconfig(struct server *server) {
2960 struct clsrvconf *conf = server->conf;
2961 struct gconffile *cf = NULL;
2963 /* for now we only learn hostname/address */
2964 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2967 debug(DBG_ERR, "dynamicconfig: pipe error");
2972 debug(DBG_ERR, "dynamicconfig: fork error");
2974 } else if (pid == 0) {
2977 if (fd[1] != STDOUT_FILENO) {
2978 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2979 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2982 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2983 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2987 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2988 ok = getgenericconfig(&cf, NULL,
2989 "Server", CONF_CBK, dynconfserver_cb, (void *)conf,
2994 if (waitpid(pid, NULL, 0) < 0) {
2995 debug(DBG_ERR, "dynamicconfig: wait error");
3003 server->conf = NULL;
3004 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
3007 int addmatchcertattr(struct clsrvconf *conf, char *matchcertattr) {
3011 if (!strncasecmp(matchcertattr, "CN:/", 4)) {
3012 r = &conf->certcnregex;
3013 v = matchcertattr + 4;
3014 } else if (!strncasecmp(matchcertattr, "SubjectAltName:URI:/", 20)) {
3015 r = &conf->certuriregex;
3016 v = matchcertattr + 20;
3021 /* regexp, remove optional trailing / if present */
3022 if (v[strlen(v) - 1] == '/')
3023 v[strlen(v) - 1] = '\0';
3027 *r = malloc(sizeof(regex_t));
3029 debug(DBG_ERR, "malloc failed");
3032 if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
3035 debug(DBG_ERR, "failed to compile regular expression %s", v);
3041 int addrewriteattr(struct clsrvconf *conf, char *rewriteattr) {
3044 v = rewriteattr + 11;
3045 if (strncasecmp(rewriteattr, "User-Name:/", 11) || !*v)
3047 /* regexp, remove optional trailing / if present */
3048 if (v[strlen(v) - 1] == '/')
3049 v[strlen(v) - 1] = '\0';
3057 conf->rewriteattrregex = malloc(sizeof(regex_t));
3058 if (!conf->rewriteattrregex) {
3059 debug(DBG_ERR, "malloc failed");
3063 conf->rewriteattrreplacement = stringcopy(w, 0);
3064 if (!conf->rewriteattrreplacement) {
3065 free(conf->rewriteattrregex);
3066 conf->rewriteattrregex = NULL;
3070 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
3071 free(conf->rewriteattrregex);
3072 conf->rewriteattrregex = NULL;
3073 free(conf->rewriteattrreplacement);
3074 conf->rewriteattrreplacement = NULL;
3075 debug(DBG_ERR, "failed to compile regular expression %s", v);
3082 /* should accept both names and numeric values, only numeric right now */
3083 uint8_t attrname2val(char *attrname) {
3086 val = atoi(attrname);
3087 return val > 0 && val < 256 ? val : 0;
3090 /* should accept both names and numeric values, only numeric right now */
3091 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
3094 *vendor = atoi(attrname);
3095 s = strchr(attrname, ':');
3100 *type = atoi(s + 1);
3101 return *type >= 0 && *type < 256;
3104 void rewritefree() {
3105 struct list_node *entry;
3106 struct rewriteconf *r;
3108 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
3109 r = (struct rewriteconf *)entry->data;
3115 list_destroy(rewriteconfs);
3116 rewriteconfs = NULL;
3119 struct rewrite *getrewrite(char *alt1, char *alt2) {
3120 struct list_node *entry;
3121 struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
3123 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
3124 r = (struct rewriteconf *)entry->data;
3125 if (!strcasecmp(r->name, alt1)) {
3129 if (!r2 && alt2 && !strcasecmp(r->name, alt2))
3140 void addrewrite(char *value, char **attrs, char **vattrs) {
3141 struct rewriteconf *new;
3142 struct rewrite *rewrite = NULL;
3145 uint32_t *p, *va = NULL;
3149 for (; attrs[n]; n++);
3150 a = malloc((n + 1) * sizeof(uint8_t));
3152 debugx(1, DBG_ERR, "malloc failed");
3154 for (i = 0; i < n; i++) {
3155 if (!(a[i] = attrname2val(attrs[i])))
3156 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
3165 for (; vattrs[n]; n++);
3166 va = malloc((2 * n + 1) * sizeof(uint32_t));
3168 debugx(1, DBG_ERR, "malloc failed");
3170 for (p = va, i = 0; i < n; i++, p += 2) {
3171 if (!vattrname2val(vattrs[i], p, p + 1))
3172 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
3180 rewrite = malloc(sizeof(struct rewrite));
3182 debugx(1, DBG_ERR, "malloc failed");
3183 rewrite->removeattrs = a;
3184 rewrite->removevendorattrs = va;
3187 new = malloc(sizeof(struct rewriteconf));
3188 if (!new || !list_push(rewriteconfs, new))
3189 debugx(1, DBG_ERR, "malloc failed");
3191 memset(new, 0, sizeof(struct rewriteconf));
3192 new->name = stringcopy(value, 0);
3194 debugx(1, DBG_ERR, "malloc failed");
3196 new->rewrite = rewrite;
3197 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3200 void confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3201 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *rewrite = NULL, *rewriteattr = NULL;
3202 struct clsrvconf *conf;
3204 debug(DBG_DBG, "confclient_cb called for %s", block);
3206 conf = malloc(sizeof(struct clsrvconf));
3207 if (!conf || !list_push(clconfs, conf))
3208 debugx(1, DBG_ERR, "malloc failed");
3209 memset(conf, 0, sizeof(struct clsrvconf));
3210 conf->certnamecheck = 1;
3212 if (!getgenericconfig(cf, block,
3213 "type", CONF_STR, &type,
3214 "host", CONF_STR, &conf->host,
3215 "secret", CONF_STR, &conf->secret,
3216 "tls", CONF_STR, &tls,
3217 "matchcertificateattribute", CONF_STR, &matchcertattr,
3218 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3219 "rewrite", CONF_STR, &rewrite,
3220 "rewriteattribute", CONF_STR, &rewriteattr,
3223 debugx(1, DBG_ERR, "configuration error");
3225 conf->name = stringcopy(val, 0);
3227 conf->host = stringcopy(val, 0);
3229 if (type && !strcasecmp(type, "udp")) {
3232 } else if (type && !strcasecmp(type, "tls")) {
3233 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultclient", "default");
3235 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3236 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
3237 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3241 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
3246 free(matchcertattr);
3248 conf->rewrite = rewrite ? getrewrite(rewrite, NULL) : getrewrite("defaultclient", "default");
3251 if (!addrewriteattr(conf, rewriteattr))
3252 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3256 if (!resolvepeer(conf, 0))
3257 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3259 if (!conf->secret) {
3260 if (conf->type == 'U')
3261 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
3262 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
3266 void confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3267 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *rewrite = NULL;
3268 struct clsrvconf *conf;
3270 debug(DBG_DBG, "confserver_cb called for %s", block);
3272 conf = malloc(sizeof(struct clsrvconf));
3273 if (!conf || !list_push(srvconfs, conf))
3274 debugx(1, DBG_ERR, "malloc failed");
3275 memset(conf, 0, sizeof(struct clsrvconf));
3276 conf->certnamecheck = 1;
3278 if (!getgenericconfig(cf, block,
3279 "type", CONF_STR, &type,
3280 "host", CONF_STR, &conf->host,
3281 "port", CONF_STR, &conf->port,
3282 "secret", CONF_STR, &conf->secret,
3283 "tls", CONF_STR, &tls,
3284 "MatchCertificateAttribute", CONF_STR, &matchcertattr,
3285 "rewrite", CONF_STR, &rewrite,
3286 "StatusServer", CONF_BLN, &conf->statusserver,
3287 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3288 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3291 debugx(1, DBG_ERR, "configuration error");
3293 conf->name = stringcopy(val, 0);
3295 conf->host = stringcopy(val, 0);
3297 if (type && !strcasecmp(type, "udp")) {
3301 conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
3302 } else if (type && !strcasecmp(type, "tls")) {
3303 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultserver", "default");
3305 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3306 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
3307 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3309 conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
3313 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
3318 free(matchcertattr);
3320 conf->rewrite = rewrite ? getrewrite(rewrite, NULL) : getrewrite("defaultserver", "default");
3322 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0))
3323 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3325 if (!conf->secret) {
3326 if (conf->type == 'U')
3327 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
3328 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
3332 void confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3333 char **servers = NULL, **accservers = NULL, *msg = NULL;
3335 debug(DBG_DBG, "confrealm_cb called for %s", block);
3337 if (!getgenericconfig(cf, block,
3338 "server", CONF_MSTR, &servers,
3339 "accountingServer", CONF_MSTR, &accservers,
3340 "ReplyMessage", CONF_STR, &msg,
3343 debugx(1, DBG_ERR, "configuration error");
3345 addrealm(realms, val, servers, accservers, msg);
3348 void conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3349 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
3351 debug(DBG_DBG, "conftls_cb called for %s", block);
3353 if (!getgenericconfig(cf, block,
3354 "CACertificateFile", CONF_STR, &cacertfile,
3355 "CACertificatePath", CONF_STR, &cacertpath,
3356 "CertificateFile", CONF_STR, &certfile,
3357 "CertificateKeyFile", CONF_STR, &certkeyfile,
3358 "CertificateKeyPassword", CONF_STR, &certkeypwd,
3361 debugx(1, DBG_ERR, "configuration error");
3363 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
3371 void confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3372 char **attrs = NULL, **vattrs = NULL;
3374 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3376 if (!getgenericconfig(cf, block,
3377 "removeAttribute", CONF_MSTR, &attrs,
3378 "removeVendorAttribute", CONF_MSTR, &vattrs,
3381 debugx(1, DBG_ERR, "configuration error");
3382 addrewrite(val, attrs, vattrs);
3385 void getmainconfig(const char *configfile) {
3386 char *loglevel = NULL;
3387 struct gconffile *cfs;
3389 cfs = openconfigfile(configfile);
3390 memset(&options, 0, sizeof(options));
3392 clconfs = list_create();
3394 debugx(1, DBG_ERR, "malloc failed");
3396 srvconfs = list_create();
3398 debugx(1, DBG_ERR, "malloc failed");
3400 realms = list_create();
3402 debugx(1, DBG_ERR, "malloc failed");
3404 tlsconfs = list_create();
3406 debugx(1, DBG_ERR, "malloc failed");
3408 rewriteconfs = list_create();
3410 debugx(1, DBG_ERR, "malloc failed");
3412 if (!getgenericconfig(&cfs, NULL,
3413 "ListenUDP", CONF_STR, &options.listenudp,
3414 "ListenTCP", CONF_STR, &options.listentcp,
3415 "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
3416 "SourceUDP", CONF_STR, &options.sourceudp,
3417 "SourceTCP", CONF_STR, &options.sourcetcp,
3418 "LogLevel", CONF_STR, &loglevel,
3419 "LogDestination", CONF_STR, &options.logdestination,
3420 "Client", CONF_CBK, confclient_cb, NULL,
3421 "Server", CONF_CBK, confserver_cb, NULL,
3422 "Realm", CONF_CBK, confrealm_cb, NULL,
3423 "TLS", CONF_CBK, conftls_cb, NULL,
3424 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3427 debugx(1, DBG_ERR, "configuration error");
3432 if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
3433 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
3434 options.loglevel = *loglevel - '0';
3439 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3442 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3445 *configfile = optarg;
3448 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3449 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3450 *loglevel = *optarg - '0';
3459 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3464 if (!(argc - optind))
3468 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3472 int daemon(int a, int b) {
3480 for (i = 0; i < 3; i++) {
3482 open("/dev/null", O_RDWR);
3488 void *sighandler(void *arg) {
3493 sigemptyset(&sigset);
3494 sigaddset(&sigset, SIGPIPE);
3495 sigwait(&sigset, &sig);
3496 /* only get SIGPIPE right now, so could simplify below code */
3499 /* completely ignoring this */
3502 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3505 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3510 int main(int argc, char **argv) {
3511 pthread_t sigth, udpserverth, udpaccserverth, udpclient4rdth, udpclient6rdth;
3513 struct list_node *entry;
3514 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3515 char *configfile = NULL;
3516 struct clsrvconf *srvconf;
3518 debug_init("radsecproxy");
3519 debug_set_level(DEBUG_LEVEL);
3520 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3522 debug_set_level(loglevel);
3523 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3525 options.loglevel = loglevel;
3526 else if (options.loglevel)
3527 debug_set_level(options.loglevel);
3529 free(options.logdestination);
3530 options.logdestination = NULL;
3532 if (!options.logdestination)
3533 options.logdestination = "x-syslog:///";
3534 debug_set_destination(options.logdestination);
3535 free(options.logdestination);
3538 if (!list_first(clconfs))
3539 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3540 if (!list_first(srvconfs))
3541 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
3542 if (!list_first(realms))
3543 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3546 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3548 if (!foreground && (daemon(0, 0) < 0))
3549 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3551 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3553 sigemptyset(&sigset);
3554 /* exit on all but SIGPIPE, ignore more? */
3555 sigaddset(&sigset, SIGPIPE);
3556 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3557 pthread_create(&sigth, NULL, sighandler, NULL);
3559 if (client_udp_count) {
3560 udp_server_replyq = newreplyq();
3561 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
3562 debugx(1, DBG_ERR, "pthread_create failed");
3563 if (options.listenaccudp)
3564 if (pthread_create(&udpaccserverth, NULL, udpaccserverrd, NULL))
3565 debugx(1, DBG_ERR, "pthread_create failed");
3568 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3569 srvconf = (struct clsrvconf *)entry->data;
3570 if (srvconf->dynamiclookupcommand)
3572 if (!addserver(srvconf))
3573 debugx(1, DBG_ERR, "failed to add server");
3574 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3575 (void *)(srvconf->servers)))
3576 debugx(1, DBG_ERR, "pthread_create failed");
3578 /* srcudpres no longer needed, while srctcpres is needed later */
3580 freeaddrinfo(srcudpres);
3583 if (udp_client4_sock >= 0)
3584 if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
3585 debugx(1, DBG_ERR, "pthread_create failed");
3586 if (udp_client6_sock >= 0)
3587 if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
3588 debugx(1, DBG_ERR, "pthread_create failed");
3590 if (client_tls_count)
3591 return tlslistener();
3593 /* just hang around doing nothing, anything to do here? */