2 * Copyright (C) 2006-2008 Stig Venaas <venaas@uninett.no>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
9 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
10 * rd is responsible for init and launching wr
11 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
12 * each tlsserverrd launches tlsserverwr
13 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
14 * for init and launching rd
16 * serverrd will receive a request, processes it and puts it in the requestq of
17 * the appropriate clientwr
18 * clientwr monitors its requestq and sends requests
19 * clientrd looks for responses, processes them and puts them in the replyq of
20 * the peer the request came from
21 * serverwr monitors its reply and sends replies
23 * In addition to the main thread, we have:
24 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
25 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
26 * For each TLS peer connecting to us there will be 2 more TLS threads
27 * This is only for connected peers
28 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
29 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
33 #include <sys/socket.h>
34 #include <netinet/in.h>
42 #include <sys/types.h>
43 #include <sys/select.h>
46 #include <arpa/inet.h>
50 #include <openssl/ssl.h>
51 #include <openssl/rand.h>
52 #include <openssl/err.h>
53 #include <openssl/md5.h>
54 #include <openssl/hmac.h>
55 #include <openssl/x509v3.h>
60 #include "radsecproxy.h"
62 static struct options options;
63 struct list *clconfs, *srvconfs, *realms, *tlsconfs, *rewriteconfs;
65 static int client_udp_count = 0;
66 static int client_tls_count = 0;
67 static int server_udp_count = 0;
68 static int server_tls_count = 0;
70 static struct addrinfo *srcudpres = NULL;
71 static struct addrinfo *srctcpres = NULL;
73 static struct replyq *udp_server_replyq = NULL;
74 static int udp_server_sock = -1;
75 static int udp_accserver_sock = -1;
76 static int udp_client4_sock = -1;
77 static int udp_client6_sock = -1;
78 static pthread_mutex_t *ssl_locks;
79 static long *ssl_lock_count;
83 /* minimum required declarations to avoid reordering code */
84 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
85 int dynamicconfig(struct server *server);
86 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
87 void freerealm(struct realm *realm);
88 void freeclsrvconf(struct clsrvconf *conf);
89 void freerqdata(struct request *rq);
91 /* callbacks for making OpenSSL thread safe */
92 unsigned long ssl_thread_id() {
93 return (unsigned long)pthread_self();
96 void ssl_locking_callback(int mode, int type, const char *file, int line) {
97 if (mode & CRYPTO_LOCK) {
98 pthread_mutex_lock(&ssl_locks[type]);
99 ssl_lock_count[type]++;
101 pthread_mutex_unlock(&ssl_locks[type]);
104 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
105 int pwdlen = strlen(userdata);
106 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
108 memcpy(buf, userdata, pwdlen);
112 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
117 err_cert = X509_STORE_CTX_get_current_cert(ctx);
118 err = X509_STORE_CTX_get_error(ctx);
119 depth = X509_STORE_CTX_get_error_depth(ctx);
121 if (depth > MAX_CERT_DEPTH) {
123 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
124 X509_STORE_CTX_set_error(ctx, err);
128 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
129 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
132 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
133 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
134 debug(DBG_WARN, "\tIssuer=%s", buf);
136 case X509_V_ERR_CERT_NOT_YET_VALID:
137 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
138 debug(DBG_WARN, "\tCertificate not yet valid");
140 case X509_V_ERR_CERT_HAS_EXPIRED:
141 debug(DBG_WARN, "Certificate has expired");
143 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
144 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
149 printf("certificate verify returns %d\n", ok);
154 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
155 struct addrinfo hints, *addrinfo, *res;
159 slash = conf->host ? strchr(conf->host, '/') : NULL;
163 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
167 if (*s < '0' || *s > '9') {
168 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
171 plen = atoi(slash + 1);
172 if (plen < 0 || plen > 128) {
173 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
178 memset(&hints, 0, sizeof(hints));
179 hints.ai_socktype = (conf->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
180 hints.ai_family = AF_UNSPEC;
181 hints.ai_flags = ai_flags;
182 if (!conf->host && !conf->port) {
183 /* getaddrinfo() doesn't like host and port to be NULL */
184 if (getaddrinfo(conf->host, DEFAULT_UDP_PORT, &hints, &addrinfo)) {
185 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
188 for (res = addrinfo; res; res = res->ai_next) {
189 switch (res->ai_family) {
191 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
194 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
200 hints.ai_flags |= AI_NUMERICHOST;
201 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
202 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
207 switch (addrinfo->ai_family) {
210 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
211 freeaddrinfo(addrinfo);
218 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
219 freeaddrinfo(addrinfo);
222 conf->prefixlen = plen;
224 conf->prefixlen = 255;
227 freeaddrinfo(conf->addrinfo);
228 conf->addrinfo = addrinfo;
232 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
234 struct addrinfo *res;
236 for (res = addrinfo; res; res = res->ai_next) {
237 if (family != AF_UNSPEC && family != res->ai_family)
239 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
241 debug(DBG_WARN, "bindtoaddr: socket failed");
245 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
248 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
251 if (!bind(s, res->ai_addr, res->ai_addrlen))
253 debug(DBG_WARN, "bindtoaddr: bind failed");
259 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
264 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
268 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
270 debugx(1, DBG_ERR, "no ] matching initial [");
274 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
277 debugx(1, DBG_ERR, "missing host/address");
279 conf->host = stringcopy(field, p - field);
282 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
283 debugx(1, DBG_ERR, "unexpected character after ]");
286 /* port number or service name is specified */;
288 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
290 debugx(1, DBG_ERR, "syntax error, : but no following port");
291 conf->port = stringcopy(field, p - field);
293 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
297 struct clsrvconf *resolve_hostport(char type, char *lconf, char *default_port) {
298 struct clsrvconf *conf;
300 conf = malloc(sizeof(struct clsrvconf));
302 debugx(1, DBG_ERR, "malloc failed");
303 memset(conf, 0, sizeof(struct clsrvconf));
306 parsehostport(lconf, conf, default_port);
307 if (!strcmp(conf->host, "*")) {
312 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
313 if (!resolvepeer(conf, AI_PASSIVE))
314 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
318 void freeclsrvres(struct clsrvconf *res) {
322 freeaddrinfo(res->addrinfo);
326 int connecttcp(struct addrinfo *addrinfo) {
328 struct addrinfo *res;
331 for (res = addrinfo; res; res = res->ai_next) {
332 s = bindtoaddr(srctcpres, res->ai_family, 1, 1);
334 debug(DBG_WARN, "connecttoserver: socket failed");
337 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
339 debug(DBG_WARN, "connecttoserver: connect failed");
346 /* returns 1 if the len first bits are equal, else 0 */
347 int prefixmatch(void *a1, void *a2, uint8_t len) {
348 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
350 if (l && memcmp(a1, a2, l))
355 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
358 /* check if conf has matching address */
359 struct clsrvconf *checkconfaddr(char type, struct sockaddr *addr, struct clsrvconf *conf) {
360 struct sockaddr_in6 *sa6 = NULL;
361 struct in_addr *a4 = NULL;
362 struct addrinfo *res;
364 if (addr->sa_family == AF_INET6) {
365 sa6 = (struct sockaddr_in6 *)addr;
366 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
367 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
371 a4 = &((struct sockaddr_in *)addr)->sin_addr;
373 if (conf->type == type) {
374 if (conf->prefixlen == 255) {
375 for (res = conf->addrinfo; res; res = res->ai_next)
376 if ((a4 && res->ai_family == AF_INET &&
377 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
378 (sa6 && res->ai_family == AF_INET6 &&
379 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
382 res = conf->addrinfo;
384 ((a4 && res->ai_family == AF_INET &&
385 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
386 (sa6 && res->ai_family == AF_INET6 &&
387 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
394 /* returns next config with matching address, or NULL */
395 struct clsrvconf *find_conf(char type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
396 struct sockaddr_in6 *sa6 = NULL;
397 struct in_addr *a4 = NULL;
398 struct addrinfo *res;
399 struct list_node *entry;
400 struct clsrvconf *conf;
402 if (addr->sa_family == AF_INET6) {
403 sa6 = (struct sockaddr_in6 *)addr;
404 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
405 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
409 a4 = &((struct sockaddr_in *)addr)->sin_addr;
411 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
412 conf = (struct clsrvconf *)entry->data;
413 if (conf->type == type) {
414 if (conf->prefixlen == 255) {
415 for (res = conf->addrinfo; res; res = res->ai_next)
416 if ((a4 && res->ai_family == AF_INET &&
417 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
418 (sa6 && res->ai_family == AF_INET6 &&
419 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
425 res = conf->addrinfo;
427 ((a4 && res->ai_family == AF_INET &&
428 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
429 (sa6 && res->ai_family == AF_INET6 &&
430 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
441 struct replyq *newreplyq() {
442 struct replyq *replyq;
444 replyq = malloc(sizeof(struct replyq));
446 debugx(1, DBG_ERR, "malloc failed");
447 replyq->replies = list_create();
448 if (!replyq->replies)
449 debugx(1, DBG_ERR, "malloc failed");
450 pthread_mutex_init(&replyq->mutex, NULL);
451 pthread_cond_init(&replyq->cond, NULL);
455 struct client *addclient(struct clsrvconf *conf) {
456 struct client *new = malloc(sizeof(struct client));
459 debug(DBG_ERR, "malloc failed");
462 if (!conf->clients) {
463 conf->clients = list_create();
464 if (!conf->clients) {
465 debug(DBG_ERR, "malloc failed");
470 memset(new, 0, sizeof(struct client));
472 new->replyq = conf->type == 'T' ? newreplyq() : udp_server_replyq;
474 list_push(conf->clients, new);
478 void removeclient(struct client *client) {
479 struct list_node *entry;
481 if (!client || !client->conf->clients)
484 pthread_mutex_lock(&client->replyq->mutex);
485 for (entry = list_first(client->replyq->replies); entry; entry = list_next(entry))
486 free(((struct reply *)entry)->buf);
487 list_destroy(client->replyq->replies);
488 pthread_cond_destroy(&client->replyq->cond);
489 pthread_mutex_unlock(&client->replyq->mutex);
490 pthread_mutex_destroy(&client->replyq->mutex);
491 list_removedata(client->conf->clients, client);
495 void removeclientrqs(struct client *client) {
496 struct list_node *entry;
497 struct server *server;
501 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
502 server = ((struct clsrvconf *)entry->data)->servers;
503 pthread_mutex_lock(&server->newrq_mutex);
504 for (i = 0; i < MAX_REQUESTS; i++) {
505 rq = server->requests + i;
506 if (rq->from == client)
509 pthread_mutex_unlock(&server->newrq_mutex);
513 void freeserver(struct server *server, uint8_t destroymutex) {
514 struct request *rq, *end;
519 if(server->requests) {
520 rq = server->requests;
521 for (end = rq + MAX_REQUESTS; rq < end; rq++)
523 free(server->requests);
525 free(server->dynamiclookuparg);
527 pthread_mutex_destroy(&server->lock);
528 pthread_cond_destroy(&server->newrq_cond);
529 pthread_mutex_destroy(&server->newrq_mutex);
534 int addserver(struct clsrvconf *conf) {
535 struct clsrvconf *res;
538 debug(DBG_ERR, "addserver: currently works with just one server per conf");
541 conf->servers = malloc(sizeof(struct server));
542 if (!conf->servers) {
543 debug(DBG_ERR, "malloc failed");
546 memset(conf->servers, 0, sizeof(struct server));
547 conf->servers->conf = conf;
549 if (conf->type == 'U') {
551 res = resolve_hostport('U', options.sourceudp, NULL);
552 srcudpres = res->addrinfo;
553 res->addrinfo = NULL;
556 switch (conf->addrinfo->ai_family) {
558 if (udp_client4_sock < 0) {
559 udp_client4_sock = bindtoaddr(srcudpres, AF_INET, 0, 1);
560 if (udp_client4_sock < 0)
561 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
563 conf->servers->sock = udp_client4_sock;
566 if (udp_client6_sock < 0) {
567 udp_client6_sock = bindtoaddr(srcudpres, AF_INET6, 0, 1);
568 if (udp_client6_sock < 0)
569 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
571 conf->servers->sock = udp_client6_sock;
574 debugx(1, DBG_ERR, "addserver: unsupported address family");
579 res = resolve_hostport('T', options.sourcetcp, NULL);
580 srctcpres = res->addrinfo;
581 res->addrinfo = NULL;
584 conf->servers->sock = -1;
587 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
588 if (!conf->servers->requests) {
589 debug(DBG_ERR, "malloc failed");
592 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
593 debug(DBG_ERR, "mutex init failed");
596 conf->servers->newrq = 0;
597 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
598 debug(DBG_ERR, "mutex init failed");
599 pthread_mutex_destroy(&conf->servers->lock);
602 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
603 debug(DBG_ERR, "mutex init failed");
604 pthread_mutex_destroy(&conf->servers->newrq_mutex);
605 pthread_mutex_destroy(&conf->servers->lock);
612 freeserver(conf->servers, 0);
613 conf->servers = NULL;
617 /* exactly one of client and server must be non-NULL */
618 /* should probably take peer list (client(s) or server(s)) as argument instead */
619 /* if *peer == NULL we return who we received from, else require it to be from peer */
620 /* return from in sa if not NULL */
621 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
623 unsigned char buf[65536], *rad;
624 struct sockaddr_storage from;
625 socklen_t fromlen = sizeof(from);
627 struct list_node *node;
630 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
632 debug(DBG_WARN, "radudpget: recv failed");
635 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
638 debug(DBG_WARN, "radudpget: packet too small");
644 debug(DBG_WARN, "radudpget: length too small");
649 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
653 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
657 p = checkconfaddr('U', (struct sockaddr *)&from, (*client)->conf);
659 p = find_conf('U', (struct sockaddr *)&from, clconfs, NULL);
662 p = checkconfaddr('U', (struct sockaddr *)&from, (*server)->conf);
664 p = find_conf('U', (struct sockaddr *)&from, srvconfs, NULL);
667 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
673 debug(DBG_ERR, "radudpget: malloc failed");
677 if (client && !*client) {
678 node = list_first(p->clients);
679 *client = node ? (struct client *)node->data : addclient(p);
684 } else if (server && !*server)
685 *server = p->servers;
689 memcpy(rad, buf, len);
695 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
696 int loc, i, l, n, r = 0;
699 STACK_OF(GENERAL_NAME) *alt;
702 debug(DBG_DBG, "subjectaltnameaddr");
704 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
708 ex = X509_get_ext(cert, loc);
709 alt = X509V3_EXT_d2i(ex);
713 n = sk_GENERAL_NAME_num(alt);
714 for (i = 0; i < n; i++) {
715 gn = sk_GENERAL_NAME_value(alt, i);
716 if (gn->type != GEN_IPADD)
719 v = (char *)ASN1_STRING_data(gn->d.ia5);
720 l = ASN1_STRING_length(gn->d.ia5);
721 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
722 && !memcmp(v, &addr, l)) {
727 GENERAL_NAMES_free(alt);
731 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
738 nm = X509_get_subject_name(cert);
741 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
744 e = X509_NAME_get_entry(nm, loc);
745 t = X509_NAME_ENTRY_get_data(e);
746 v = (char *) ASN1_STRING_data(t);
747 l = ASN1_STRING_length(t);
751 if (l == strlen(exact) && !strncasecmp(exact, v, l))
754 s = stringcopy((char *)v, l);
756 debug(DBG_ERR, "malloc failed");
759 if (regexec(regex, s, 0, NULL, 0)) {
770 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
771 int loc, i, l, n, r = 0;
774 STACK_OF(GENERAL_NAME) *alt;
777 debug(DBG_DBG, "subjectaltnameregexp");
779 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
783 ex = X509_get_ext(cert, loc);
784 alt = X509V3_EXT_d2i(ex);
788 n = sk_GENERAL_NAME_num(alt);
789 for (i = 0; i < n; i++) {
790 gn = sk_GENERAL_NAME_value(alt, i);
791 if (gn->type != type)
794 v = (char *)ASN1_STRING_data(gn->d.ia5);
795 l = ASN1_STRING_length(gn->d.ia5);
799 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
802 if (memcmp(v, exact, l))
805 s = stringcopy((char *)v, l);
807 debug(DBG_ERR, "malloc failed");
810 if (regexec(regex, s, 0, NULL, 0)) {
819 GENERAL_NAMES_free(alt);
823 X509 *verifytlscert(SSL *ssl) {
827 if (SSL_get_verify_result(ssl) != X509_V_OK) {
828 debug(DBG_ERR, "verifytlscert: basic validation failed");
829 while ((error = ERR_get_error()))
830 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
834 cert = SSL_get_peer_certificate(ssl);
836 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
840 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
842 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
843 struct in6_addr addr;
845 if (conf->certnamecheck && conf->prefixlen == 255) {
846 if (inet_pton(AF_INET, conf->host, &addr))
848 else if (inet_pton(AF_INET6, conf->host, &addr))
851 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
854 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
857 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
859 if (!cnregexp(cert, conf->host, NULL)) {
860 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
863 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
866 if (conf->certcnregex) {
867 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
868 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
871 debug(DBG_DBG, "verifyconfcert: CN matching regex");
873 if (conf->certuriregex) {
874 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
875 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
878 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
883 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
888 debug(DBG_DBG, "tlsconnect called from %s", text);
889 pthread_mutex_lock(&server->lock);
890 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
891 /* already reconnected, nothing to do */
892 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
893 pthread_mutex_unlock(&server->lock);
897 debug(DBG_DBG, "tlsconnect %s", text);
900 gettimeofday(&now, NULL);
901 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
902 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
903 debug(DBG_DBG, "tlsconnect: timeout");
904 if (server->sock >= 0)
906 SSL_free(server->ssl);
908 pthread_mutex_unlock(&server->lock);
911 if (server->connectionok) {
912 server->connectionok = 0;
914 } else if (elapsed < 1)
916 else if (elapsed < 60) {
917 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
919 } else if (elapsed < 100000) {
920 debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
923 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
924 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
925 if (server->sock >= 0)
927 if ((server->sock = connecttcp(server->conf->addrinfo)) < 0) {
928 debug(DBG_ERR, "tlsconnect: connecttcp failed");
932 SSL_free(server->ssl);
933 server->ssl = SSL_new(server->conf->ssl_ctx);
934 SSL_set_fd(server->ssl, server->sock);
935 if (SSL_connect(server->ssl) <= 0)
937 cert = verifytlscert(server->ssl);
940 if (verifyconfcert(cert, server->conf)) {
946 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
947 gettimeofday(&server->lastconnecttry, NULL);
948 pthread_mutex_unlock(&server->lock);
952 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
953 /* returns 0 on timeout, -1 on error and num if ok */
954 int sslreadtimeout(SSL *ssl, unsigned char *buf, int num, int timeout) {
955 int s, ndesc, cnt, len;
956 fd_set readfds, writefds;
957 struct timeval timer;
962 /* make socket non-blocking? */
963 for (len = 0; len < num; len += cnt) {
968 timer.tv_sec = timeout;
971 ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
975 cnt = SSL_read(ssl, buf + len, num - len);
977 switch (SSL_get_error(ssl, cnt)) {
978 case SSL_ERROR_WANT_READ:
979 case SSL_ERROR_WANT_WRITE:
982 case SSL_ERROR_ZERO_RETURN:
983 /* remote end sent close_notify, send one back */
993 /* timeout in seconds, 0 means no timeout (blocking) */
994 unsigned char *radtlsget(SSL *ssl, int timeout) {
996 unsigned char buf[4], *rad;
999 cnt = sslreadtimeout(ssl, buf, 4, timeout);
1001 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1008 debug(DBG_ERR, "radtlsget: malloc failed");
1011 memcpy(rad, buf, 4);
1013 cnt = sslreadtimeout(ssl, rad + 4, len - 4, timeout);
1015 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1024 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
1027 debug(DBG_DBG, "radtlsget: got %d bytes", total);
1031 int clientradputudp(struct server *server, unsigned char *rad) {
1033 struct sockaddr_storage sa;
1034 struct sockaddr *sap;
1035 struct clsrvconf *conf = server->conf;
1036 in_port_t *port = NULL;
1040 if (*rad == RAD_Accounting_Request) {
1041 sap = (struct sockaddr *)&sa;
1042 memcpy(sap, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen);
1044 sap = conf->addrinfo->ai_addr;
1046 switch (sap->sa_family) {
1048 port = &((struct sockaddr_in *)sap)->sin_port;
1051 port = &((struct sockaddr_in6 *)sap)->sin6_port;
1057 if (*rad == RAD_Accounting_Request)
1058 *port = htons(ntohs(*port) + 1);
1060 if (sendto(server->sock, rad, len, 0, sap, conf->addrinfo->ai_addrlen) >= 0) {
1061 debug(DBG_DBG, "clienradputudp: sent UDP of length %d to %s port %d", len, conf->host, ntohs(*port));
1065 debug(DBG_WARN, "clientradputudp: send failed");
1069 int clientradputtls(struct server *server, unsigned char *rad) {
1072 unsigned long error;
1073 struct timeval lastconnecttry;
1074 struct clsrvconf *conf = server->conf;
1077 lastconnecttry = server->lastconnecttry;
1078 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
1079 while ((error = ERR_get_error()))
1080 debug(DBG_ERR, "clientradputtls: TLS: %s", ERR_error_string(error, NULL));
1081 if (server->dynamiclookuparg)
1083 tlsconnect(server, &lastconnecttry, 0, "clientradputtls");
1084 lastconnecttry = server->lastconnecttry;
1087 server->connectionok = 1;
1088 debug(DBG_DBG, "clientradputtls: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
1092 int clientradput(struct server *server, unsigned char *rad) {
1093 switch (server->conf->type) {
1095 return clientradputudp(server, rad);
1097 return clientradputtls(server, rad);
1102 int radsign(unsigned char *rad, unsigned char *sec) {
1103 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1104 static unsigned char first = 1;
1105 static EVP_MD_CTX mdctx;
1106 unsigned int md_len;
1109 pthread_mutex_lock(&lock);
1111 EVP_MD_CTX_init(&mdctx);
1115 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1116 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
1117 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1118 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
1120 pthread_mutex_unlock(&lock);
1124 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
1125 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1126 static unsigned char first = 1;
1127 static EVP_MD_CTX mdctx;
1128 unsigned char hash[EVP_MAX_MD_SIZE];
1132 pthread_mutex_lock(&lock);
1134 EVP_MD_CTX_init(&mdctx);
1140 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1141 EVP_DigestUpdate(&mdctx, rad, 4) &&
1142 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
1143 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
1144 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1145 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
1147 !memcmp(hash, rad + 4, 16));
1148 pthread_mutex_unlock(&lock);
1152 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
1153 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1154 static unsigned char first = 1;
1155 static HMAC_CTX hmacctx;
1156 unsigned int md_len;
1157 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
1159 pthread_mutex_lock(&lock);
1161 HMAC_CTX_init(&hmacctx);
1165 memcpy(auth, authattr, 16);
1166 memset(authattr, 0, 16);
1168 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1169 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1170 HMAC_Final(&hmacctx, hash, &md_len);
1171 memcpy(authattr, auth, 16);
1173 debug(DBG_WARN, "message auth computation failed");
1174 pthread_mutex_unlock(&lock);
1178 if (memcmp(auth, hash, 16)) {
1179 debug(DBG_WARN, "message authenticator, wrong value");
1180 pthread_mutex_unlock(&lock);
1184 pthread_mutex_unlock(&lock);
1188 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
1189 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1190 static unsigned char first = 1;
1191 static HMAC_CTX hmacctx;
1192 unsigned int md_len;
1197 pthread_mutex_lock(&lock);
1199 HMAC_CTX_init(&hmacctx);
1203 memset(authattrval, 0, 16);
1205 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1206 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1207 HMAC_Final(&hmacctx, authattrval, &md_len);
1209 debug(DBG_WARN, "message auth computation failed");
1210 pthread_mutex_unlock(&lock);
1214 pthread_mutex_unlock(&lock);
1218 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
1219 while (length > 1) {
1220 if (ATTRTYPE(attrs) == type)
1222 length -= ATTRLEN(attrs);
1223 attrs += ATTRLEN(attrs);
1228 void freerqdata(struct request *rq) {
1229 if (rq->origusername)
1230 free(rq->origusername);
1235 void sendrq(struct server *to, struct request *rq) {
1239 pthread_mutex_lock(&to->newrq_mutex);
1240 /* might simplify if only try nextid, might be ok */
1241 for (i = to->nextid; i < MAX_REQUESTS; i++)
1242 if (!to->requests[i].buf)
1244 if (i == MAX_REQUESTS) {
1245 for (i = 0; i < to->nextid; i++)
1246 if (!to->requests[i].buf)
1248 if (i == to->nextid) {
1249 debug(DBG_WARN, "No room in queue, dropping request");
1251 pthread_mutex_unlock(&to->newrq_mutex);
1256 rq->buf[1] = (char)i;
1258 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1259 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1261 pthread_mutex_unlock(&to->newrq_mutex);
1265 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1266 to->requests[i] = *rq;
1271 debug(DBG_DBG, "signalling client writer");
1272 pthread_cond_signal(&to->newrq_cond);
1274 pthread_mutex_unlock(&to->newrq_mutex);
1277 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
1278 struct reply *reply;
1281 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1283 debug(DBG_WARN, "sendreply: failed to sign message");
1287 reply = malloc(sizeof(struct reply));
1290 debug(DBG_ERR, "sendreply: malloc failed");
1293 memset(reply, 0, sizeof(struct reply));
1296 reply->tosa = *tosa;
1298 pthread_mutex_lock(&to->replyq->mutex);
1300 first = list_first(to->replyq->replies) == NULL;
1302 if (!list_push(to->replyq->replies, reply)) {
1303 pthread_mutex_unlock(&to->replyq->mutex);
1306 debug(DBG_ERR, "sendreply: malloc failed");
1311 debug(DBG_DBG, "signalling server writer");
1312 pthread_cond_signal(&to->replyq->cond);
1314 pthread_mutex_unlock(&to->replyq->mutex);
1317 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1318 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1319 static unsigned char first = 1;
1320 static EVP_MD_CTX mdctx;
1321 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1322 unsigned int md_len;
1323 uint8_t i, offset = 0, out[128];
1325 pthread_mutex_lock(&lock);
1327 EVP_MD_CTX_init(&mdctx);
1333 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1334 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1335 !EVP_DigestUpdate(&mdctx, input, 16) ||
1336 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1338 pthread_mutex_unlock(&lock);
1341 for (i = 0; i < 16; i++)
1342 out[offset + i] = hash[i] ^ in[offset + i];
1343 input = out + offset - 16;
1348 memcpy(in, out, len);
1349 pthread_mutex_unlock(&lock);
1353 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1354 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1355 static unsigned char first = 1;
1356 static EVP_MD_CTX mdctx;
1357 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1358 unsigned int md_len;
1359 uint8_t i, offset = 0, out[128];
1361 pthread_mutex_lock(&lock);
1363 EVP_MD_CTX_init(&mdctx);
1369 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1370 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1371 !EVP_DigestUpdate(&mdctx, input, 16) ||
1372 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1374 pthread_mutex_unlock(&lock);
1377 for (i = 0; i < 16; i++)
1378 out[offset + i] = hash[i] ^ in[offset + i];
1379 input = in + offset;
1384 memcpy(in, out, len);
1385 pthread_mutex_unlock(&lock);
1389 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1390 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1391 static unsigned char first = 1;
1392 static EVP_MD_CTX mdctx;
1393 unsigned char hash[EVP_MAX_MD_SIZE];
1394 unsigned int md_len;
1397 pthread_mutex_lock(&lock);
1399 EVP_MD_CTX_init(&mdctx);
1404 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1405 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1406 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1409 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1410 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1411 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1412 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1413 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1414 pthread_mutex_unlock(&lock);
1419 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1422 for (i = 0; i < 16; i++)
1425 for (offset = 16; offset < len; offset += 16) {
1427 printf("text + offset - 16 c(%d): ", offset / 16);
1428 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1430 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1431 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1432 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1433 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1435 pthread_mutex_unlock(&lock);
1439 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1442 for (i = 0; i < 16; i++)
1443 text[offset + i] ^= hash[i];
1447 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1450 pthread_mutex_unlock(&lock);
1454 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1455 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1456 static unsigned char first = 1;
1457 static EVP_MD_CTX mdctx;
1458 unsigned char hash[EVP_MAX_MD_SIZE];
1459 unsigned int md_len;
1463 pthread_mutex_lock(&lock);
1465 EVP_MD_CTX_init(&mdctx);
1470 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1471 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1472 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1475 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1476 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1477 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1478 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1479 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1480 pthread_mutex_unlock(&lock);
1485 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1488 for (i = 0; i < 16; i++)
1489 plain[i] = text[i] ^ hash[i];
1491 for (offset = 16; offset < len; offset += 16) {
1493 printf("text + offset - 16 c(%d): ", offset / 16);
1494 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1496 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1497 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1498 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1499 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1501 pthread_mutex_unlock(&lock);
1505 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1508 for (i = 0; i < 16; i++)
1509 plain[offset + i] = text[offset + i] ^ hash[i];
1512 memcpy(text, plain, len);
1514 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1517 pthread_mutex_unlock(&lock);
1521 struct realm *id2realm(struct list *realmlist, char *id) {
1522 struct list_node *entry;
1523 struct realm *realm, *subrealm = NULL;
1525 /* need to do locking for subrealms and check subrealm timers */
1526 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1527 realm = (struct realm *)entry->data;
1528 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1529 pthread_mutex_lock(&realm->subrealms_mutex);
1530 if (realm->subrealms)
1531 subrealm = id2realm(realm->subrealms, id);
1532 pthread_mutex_unlock(&realm->subrealms_mutex);
1533 return subrealm ? subrealm : realm;
1539 /* helper function, only used by removeserversubrealms() */
1540 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1541 struct list_node *entry;
1542 struct realm *realm;
1544 for (entry = list_first(realmlist); entry;) {
1545 realm = (struct realm *)entry->data;
1546 entry = list_next(entry);
1547 if (realm->srvconfs) {
1548 list_removedata(realm->srvconfs, srv);
1549 if (!list_first(realm->srvconfs)) {
1550 list_destroy(realm->srvconfs);
1551 realm->srvconfs = NULL;
1554 if (realm->accsrvconfs) {
1555 list_removedata(realm->accsrvconfs, srv);
1556 if (!list_first(realm->accsrvconfs)) {
1557 list_destroy(realm->accsrvconfs);
1558 realm->accsrvconfs = NULL;
1562 /* remove subrealm if no servers */
1563 if (!realm->srvconfs && !realm->accsrvconfs) {
1564 list_removedata(realmlist, realm);
1570 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1571 struct list_node *entry;
1572 struct realm *realm;
1574 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1575 realm = (struct realm *)entry->data;
1576 pthread_mutex_lock(&realm->subrealms_mutex);
1577 if (realm->subrealms) {
1578 _internal_removeserversubrealms(realm->subrealms, srv);
1579 if (!list_first(realm->subrealms)) {
1580 list_destroy(realm->subrealms);
1581 realm->subrealms = NULL;
1584 pthread_mutex_unlock(&realm->subrealms_mutex);
1588 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1589 struct request *rq = to->requests, *end;
1591 pthread_mutex_lock(&to->newrq_mutex);
1592 for (end = rq + MAX_REQUESTS; rq < end; rq++)
1593 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1595 pthread_mutex_unlock(&to->newrq_mutex);
1600 int attrvalidate(unsigned char *attrs, int length) {
1601 while (length > 1) {
1602 if (ATTRLEN(attrs) < 2) {
1603 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1606 length -= ATTRLEN(attrs);
1608 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1611 attrs += ATTRLEN(attrs);
1614 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1618 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1619 if (len < 16 || len > 128 || len % 16) {
1620 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1624 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1625 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1629 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1631 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1632 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1638 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1641 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1642 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1645 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1646 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1652 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1653 char *oldsecret, char *newsecret) {
1654 unsigned char *attr;
1656 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1657 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1658 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1664 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1668 for (; attrs[0]; attrs += 2)
1669 if (attrs[0] == vendor && attrs[1] == subattr)
1674 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1675 uint8_t alen, sublen, rmlen = 0;
1676 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1679 if (!removevendorattrs)
1682 while (*removevendorattrs && *removevendorattrs != vendor)
1683 removevendorattrs += 2;
1684 if (!*removevendorattrs)
1687 alen = ATTRLEN(attrs);
1689 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1690 /* remove entire vendor attribute */
1691 memmove(attrs, attrs + alen, length - alen);
1696 subattrs = ATTRVAL(attrs) + 4;
1698 if (!attrvalidate(subattrs, sublen)) {
1699 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1704 while (sublen > 1) {
1705 alen = ATTRLEN(subattrs);
1708 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1709 memmove(subattrs, subattrs + alen, length);
1715 ATTRLEN(attrs) -= rmlen;
1719 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1720 uint8_t *attrs, alen;
1721 uint16_t len, rmlen = 0;
1723 if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1726 len = RADLEN(buf) - 20;
1729 alen = ATTRLEN(attrs);
1731 if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1732 memmove(attrs, attrs + alen, len);
1734 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1735 rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1740 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1743 /* returns a pointer to the resized attribute value */
1744 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1745 uint8_t *attrs, *attr, vallen;
1749 len = RADLEN(*buf) - 20;
1752 attr = attrget(attrs, len, type);
1756 vallen = ATTRVALLEN(attr);
1757 if (vallen == newvallen)
1760 len += newvallen - vallen;
1761 if (newvallen > vallen) {
1762 new = realloc(*buf, len + 20);
1764 debug(DBG_ERR, "resizeattr: malloc failed");
1773 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1774 attr[1] = newvallen + 2;
1775 ((uint16_t *)*buf)[1] = htons(len + 20);
1779 int rewriteusername(struct request *rq, char *in) {
1780 size_t nmatch = 10, reslen = 0, start = 0;
1781 regmatch_t pmatch[10], *pfield;
1783 unsigned char *result;
1784 char *out = rq->from->conf->rewriteattrreplacement;
1786 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1787 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1791 rq->origusername = stringcopy(in, 0);
1792 if (!rq->origusername)
1795 for (i = start; out[i]; i++) {
1796 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1797 pfield = &pmatch[out[i + 1] - '0'];
1798 if (pfield->rm_so >= 0) {
1799 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1805 reslen += i - start;
1807 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1813 for (i = start; out[i]; i++) {
1814 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1815 pfield = &pmatch[out[i + 1] - '0'];
1816 if (pfield->rm_so >= 0) {
1817 memcpy(result + reslen, out + start, i - start);
1818 reslen += i - start;
1819 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1820 reslen += pfield->rm_eo - pfield->rm_so;
1827 memcpy(result + reslen, out + start, i - start);
1828 reslen += i - start;
1829 memcpy(in, result, reslen);
1834 const char *radmsgtype2string(uint8_t code) {
1835 static const char *rad_msg_names[] = {
1836 "", "Access-Request", "Access-Accept", "Access-Reject",
1837 "Accounting-Request", "Accounting-Response", "", "",
1838 "", "", "", "Access-Challenge",
1839 "Status-Server", "Status-Client"
1841 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1844 void char2hex(char *h, unsigned char c) {
1845 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1846 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1847 h[0] = hexdigits[c / 16];
1848 h[1] = hexdigits[c % 16];
1852 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
1856 if (!attr || len == 1) {
1861 l = ATTRVALLEN(attr);
1862 s = (char *)ATTRVAL(attr);
1865 for (i = 0; i < l; i++) {
1866 if (s[i] > 31 && s[i] < 127) {
1868 if (d - ascii == len - 1)
1871 if (d - ascii > len - 4)
1876 if (d - ascii == len - 1)
1884 void acclog(unsigned char *attrs, int length, char *host) {
1885 unsigned char *attr;
1888 attr = attrget(attrs, length, RAD_Attr_User_Name);
1890 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1893 radattr2ascii(username, sizeof(username), attr);
1894 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1897 void respondaccounting(struct request *rq) {
1898 unsigned char *resp;
1902 debug(DBG_ERR, "respondstatusserver: malloc failed");
1905 memcpy(resp, rq->buf, 20);
1906 resp[0] = RAD_Accounting_Response;
1909 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1910 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1913 void respondstatusserver(struct request *rq) {
1914 unsigned char *resp;
1918 debug(DBG_ERR, "respondstatusserver: malloc failed");
1921 memcpy(resp, rq->buf, 20);
1922 resp[0] = RAD_Access_Accept;
1925 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1926 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1929 void respondreject(struct request *rq, char *message) {
1930 unsigned char *resp;
1933 if (message && *message)
1934 len += 2 + strlen(message);
1938 debug(DBG_ERR, "respondreject: malloc failed");
1941 memcpy(resp, rq->buf, 20);
1942 resp[0] = RAD_Access_Reject;
1943 *(uint16_t *)(resp + 2) = htons(len);
1944 if (message && *message) {
1945 resp[20] = RAD_Attr_Reply_Message;
1946 resp[21] = len - 20;
1947 memcpy(resp + 22, message, len - 22);
1949 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1952 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1953 struct list_node *entry;
1954 struct clsrvconf *server, *best = NULL, *first = NULL;
1956 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1957 server = (struct clsrvconf *)entry->data;
1958 if (!server->servers)
1962 if (!server->servers->connectionok)
1964 if (!server->servers->lostrqs)
1970 if (server->servers->lostrqs < best->servers->lostrqs)
1973 return best ? best : first;
1976 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
1977 struct clsrvconf *srvconf;
1979 *realm = id2realm(realms, id);
1982 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1983 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1986 if (!acc && !srvconf->servers)
1987 adddynamicrealmserver(*realm, srvconf, id);
1988 return srvconf->servers;
1991 void radsrv(struct request *rq) {
1992 uint8_t code, id, *auth, *attrs, *attr;
1994 struct server *to = NULL;
1995 char username[254], userascii[760];
1996 unsigned char newauth[16];
1997 struct realm *realm = NULL;
1999 code = *(uint8_t *)rq->buf;
2000 id = *(uint8_t *)(rq->buf + 1);
2001 len = RADLEN(rq->buf);
2002 auth = (uint8_t *)(rq->buf + 4);
2004 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
2006 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
2007 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
2012 attrs = rq->buf + 20;
2014 if (!attrvalidate(attrs, len)) {
2015 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
2019 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2020 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
2021 debug(DBG_WARN, "radsrv: message authentication failed");
2025 if (code == RAD_Status_Server) {
2026 respondstatusserver(rq);
2030 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
2032 if (rq->from->conf->rewrite) {
2033 dorewrite(rq->buf, rq->from->conf->rewrite);
2034 len = RADLEN(rq->buf) - 20;
2037 attr = attrget(attrs, len, RAD_Attr_User_Name);
2039 if (code == RAD_Accounting_Request) {
2040 acclog(attrs, len, rq->from->conf->host);
2041 respondaccounting(rq);
2043 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
2046 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
2047 username[ATTRVALLEN(attr)] = '\0';
2048 radattr2ascii(userascii, sizeof(userascii), attr);
2050 if (rq->from->conf->rewriteattrregex) {
2051 if (!rewriteusername(rq, username)) {
2052 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
2055 len = RADLEN(rq->buf) - 20;
2056 auth = (uint8_t *)(rq->buf + 4);
2057 attrs = rq->buf + 20;
2060 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
2062 to = findserver(&realm, username, code == RAD_Accounting_Request);
2064 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
2068 if (realm->message && code == RAD_Access_Request) {
2069 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
2070 respondreject(rq, realm->message);
2075 if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
2076 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
2077 rq->from->conf->name, to->conf->name);
2081 if (rqinqueue(to, rq->from, id, code)) {
2082 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
2083 radmsgtype2string(code), rq->from->conf->host, id);
2087 if (!RAND_bytes(newauth, 16)) {
2088 debug(DBG_WARN, "radsrv: failed to generate random auth");
2093 printfchars(NULL, "auth", "%02x ", auth, 16);
2096 attr = attrget(attrs, len, RAD_Attr_User_Password);
2098 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
2099 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2103 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
2105 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
2106 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2111 memcpy(rq->origauth, auth, 16);
2112 memcpy(auth, newauth, 16);
2120 int replyh(struct server *server, unsigned char *buf) {
2121 struct client *from;
2124 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
2125 struct sockaddr_storage fromsa;
2126 char tmp[760], stationid[760];
2128 server->connectionok = 1;
2129 server->lostrqs = 0;
2131 i = buf[1]; /* i is the id */
2133 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
2134 && *buf != RAD_Accounting_Response) {
2135 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
2138 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
2140 rq = server->requests + i;
2142 pthread_mutex_lock(&server->newrq_mutex);
2143 if (!rq->buf || !rq->tries) {
2144 pthread_mutex_unlock(&server->newrq_mutex);
2145 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
2150 pthread_mutex_unlock(&server->newrq_mutex);
2151 debug(DBG_INFO, "replyh: already received, ignoring reply");
2155 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
2156 pthread_mutex_unlock(&server->newrq_mutex);
2157 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
2161 len = RADLEN(buf) - 20;
2164 if (!attrvalidate(attrs, len)) {
2165 pthread_mutex_unlock(&server->newrq_mutex);
2166 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
2170 /* Message Authenticator */
2171 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2173 if (ATTRVALLEN(messageauth) != 16) {
2174 pthread_mutex_unlock(&server->newrq_mutex);
2175 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
2178 memcpy(tmp, buf + 4, 16);
2179 memcpy(buf + 4, rq->buf + 4, 16);
2180 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
2181 pthread_mutex_unlock(&server->newrq_mutex);
2182 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
2185 memcpy(buf + 4, tmp, 16);
2186 debug(DBG_DBG, "replyh: message auth ok");
2189 if (*rq->buf == RAD_Status_Server) {
2191 pthread_mutex_unlock(&server->newrq_mutex);
2192 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2196 gettimeofday(&server->lastreply, NULL);
2200 pthread_mutex_unlock(&server->newrq_mutex);
2201 debug(DBG_INFO, "replyh: client gone, ignoring reply");
2205 if (server->conf->rewrite) {
2206 dorewrite(buf, server->conf->rewrite);
2207 len = RADLEN(buf) - 20;
2211 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2212 if (ATTRVALLEN(attr) <= 4)
2215 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
2218 sublen = ATTRVALLEN(attr) - 4;
2219 subattrs = ATTRVAL(attr) + 4;
2220 if (!attrvalidate(subattrs, sublen) ||
2221 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2222 rq, server->conf->secret, from->conf->secret) ||
2223 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2224 rq, server->conf->secret, from->conf->secret))
2228 pthread_mutex_unlock(&server->newrq_mutex);
2229 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2233 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2234 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2236 radattr2ascii(tmp, sizeof(tmp), attr);
2237 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2239 radattr2ascii(stationid, sizeof(stationid), attr);
2240 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2241 radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2243 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2247 buf[1] = (char)rq->origid;
2248 memcpy(buf + 4, rq->origauth, 16);
2250 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2253 if (rq->origusername) {
2254 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2256 pthread_mutex_unlock(&server->newrq_mutex);
2257 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2260 memcpy(username, rq->origusername, strlen(rq->origusername));
2261 len = RADLEN(buf) - 20;
2264 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2268 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2269 pthread_mutex_unlock(&server->newrq_mutex);
2270 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2273 debug(DBG_DBG, "replyh: computed messageauthattr");
2276 if (from->conf->type == 'U')
2277 fromsa = rq->fromsa;
2278 /* once we set received = 1, rq may be reused */
2281 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2282 sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
2283 pthread_mutex_unlock(&server->newrq_mutex);
2287 void *udpclientrd(void *arg) {
2288 struct server *server;
2290 int *s = (int *)arg;
2294 buf = radudpget(*s, NULL, &server, NULL);
2295 if (!replyh(server, buf))
2300 void *tlsclientrd(void *arg) {
2301 struct server *server = (struct server *)arg;
2303 struct timeval now, lastconnecttry;
2306 /* yes, lastconnecttry is really necessary */
2307 lastconnecttry = server->lastconnecttry;
2308 buf = radtlsget(server->ssl, server->dynamiclookuparg ? IDLE_TIMEOUT : 0);
2310 if (server->dynamiclookuparg)
2312 tlsconnect(server, &lastconnecttry, 0, "clientrd");
2316 if (!replyh(server, buf))
2318 if (server->dynamiclookuparg) {
2319 gettimeofday(&now, NULL);
2320 if (now.tv_sec - server->lastreply.tv_sec > IDLE_TIMEOUT) {
2321 debug(DBG_INFO, "clientrd: idle timeout for %s", server->conf->name);
2326 server->clientrdgone = 1;
2330 /* code for removing state not finished */
2331 void *clientwr(void *arg) {
2332 struct server *server = (struct server *)arg;
2334 pthread_t tlsclientrdth;
2335 int i, dynconffail = 0;
2337 struct timeval now, lastsend;
2338 struct timespec timeout;
2339 struct request statsrvrq;
2340 unsigned char statsrvbuf[38];
2341 struct clsrvconf *conf;
2343 conf = server->conf;
2345 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2350 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2351 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2355 memset(&timeout, 0, sizeof(struct timespec));
2357 if (conf->statusserver) {
2358 memset(&statsrvrq, 0, sizeof(struct request));
2359 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2360 statsrvbuf[0] = RAD_Status_Server;
2362 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2363 statsrvbuf[21] = 18;
2364 gettimeofday(&lastsend, NULL);
2367 if (conf->type == 'U') {
2368 server->connectionok = 1;
2370 if (!tlsconnect(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2372 server->connectionok = 1;
2373 if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server)) {
2374 debug(DBG_ERR, "clientwr: pthread_create failed");
2380 pthread_mutex_lock(&server->newrq_mutex);
2381 if (!server->newrq) {
2382 gettimeofday(&now, NULL);
2383 /* random 0-7 seconds */
2384 RAND_bytes(&rnd, 1);
2386 if (conf->statusserver) {
2387 if (!timeout.tv_sec || timeout.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
2388 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
2390 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2391 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2393 if (timeout.tv_sec > now.tv_sec)
2394 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2395 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2398 if (server->newrq) {
2399 debug(DBG_DBG, "clientwr: got new request");
2402 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2403 pthread_mutex_unlock(&server->newrq_mutex);
2405 for (i = 0; i < MAX_REQUESTS; i++) {
2406 if (server->clientrdgone) {
2407 pthread_join(tlsclientrdth, NULL);
2410 pthread_mutex_lock(&server->newrq_mutex);
2411 while (i < MAX_REQUESTS && !server->requests[i].buf)
2413 if (i == MAX_REQUESTS) {
2414 pthread_mutex_unlock(&server->newrq_mutex);
2417 rq = server->requests + i;
2420 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2422 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2424 /* setting this to NULL means that it can be reused */
2427 pthread_mutex_unlock(&server->newrq_mutex);
2431 gettimeofday(&now, NULL);
2432 if (now.tv_sec < rq->expiry.tv_sec) {
2433 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2434 timeout.tv_sec = rq->expiry.tv_sec;
2435 pthread_mutex_unlock(&server->newrq_mutex);
2439 if (rq->tries == (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
2440 ? 1 : REQUEST_RETRIES)) {
2441 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2442 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2443 if (server->lostrqs < 255)
2446 /* setting this to NULL means that it can be reused */
2448 pthread_mutex_unlock(&server->newrq_mutex);
2451 pthread_mutex_unlock(&server->newrq_mutex);
2453 rq->expiry.tv_sec = now.tv_sec +
2454 (*rq->buf == RAD_Status_Server || conf->type == 'T'
2455 ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
2456 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2457 timeout.tv_sec = rq->expiry.tv_sec;
2459 clientradput(server, server->requests[i].buf);
2460 gettimeofday(&lastsend, NULL);
2462 if (conf->statusserver) {
2463 gettimeofday(&now, NULL);
2464 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
2465 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2466 debug(DBG_WARN, "clientwr: failed to generate random auth");
2469 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2470 if (!statsrvrq.buf) {
2471 debug(DBG_ERR, "clientwr: malloc failed");
2474 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2475 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2476 lastsend.tv_sec = now.tv_sec;
2477 sendrq(server, &statsrvrq);
2482 conf->servers = NULL;
2483 if (server->dynamiclookuparg) {
2484 removeserversubrealms(realms, conf);
2488 freeclsrvconf(conf);
2490 freeserver(server, 1);
2494 void *udpserverwr(void *arg) {
2495 struct replyq *replyq = udp_server_replyq;
2496 struct reply *reply;
2499 pthread_mutex_lock(&replyq->mutex);
2500 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2501 debug(DBG_DBG, "udp server writer, waiting for signal");
2502 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2503 debug(DBG_DBG, "udp server writer, got signal");
2505 pthread_mutex_unlock(&replyq->mutex);
2507 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
2508 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2509 debug(DBG_WARN, "sendudp: send failed");
2515 void *udpserverrd(void *arg) {
2517 pthread_t udpserverwrth;
2518 struct clsrvconf *listenres;
2520 listenres = resolve_hostport('U', options.listenudp, DEFAULT_UDP_PORT);
2521 if ((udp_server_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2522 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2524 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
2525 listenres->host ? listenres->host : "*", listenres->port);
2526 freeclsrvres(listenres);
2528 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
2529 debugx(1, DBG_ERR, "pthread_create failed");
2532 memset(&rq, 0, sizeof(struct request));
2533 rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
2538 void *udpaccserverrd(void *arg) {
2540 struct clsrvconf *listenres;
2542 listenres = resolve_hostport('U', options.listenaccudp, DEFAULT_UDP_PORT);
2543 if ((udp_accserver_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2544 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2546 debug(DBG_WARN, "udpaccserverrd: listening for UDP on %s:%s",
2547 listenres->host ? listenres->host : "*", listenres->port);
2548 freeclsrvres(listenres);
2551 memset(&rq, 0, sizeof(struct request));
2552 rq.buf = radudpget(udp_accserver_sock, &rq.from, NULL, &rq.fromsa);
2553 if (*(uint8_t *)rq.buf == RAD_Accounting_Request) {
2557 debug(DBG_INFO, "udpaccserverrd: got something other than accounting-request, ignoring");
2562 void *tlsserverwr(void *arg) {
2564 unsigned long error;
2565 struct client *client = (struct client *)arg;
2566 struct replyq *replyq;
2567 struct reply *reply;
2569 debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
2570 replyq = client->replyq;
2572 pthread_mutex_lock(&replyq->mutex);
2573 while (!list_first(replyq->replies)) {
2575 debug(DBG_DBG, "tls server writer, waiting for signal");
2576 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2577 debug(DBG_DBG, "tls server writer, got signal");
2580 /* ssl might have changed while waiting */
2581 pthread_mutex_unlock(&replyq->mutex);
2582 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2586 reply = (struct reply *)list_shift(replyq->replies);
2587 pthread_mutex_unlock(&replyq->mutex);
2588 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2590 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
2591 cnt, RADLEN(reply->buf));
2593 while ((error = ERR_get_error()))
2594 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2600 void tlsserverrd(struct client *client) {
2602 pthread_t tlsserverwrth;
2604 debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2606 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2607 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2612 memset(&rq, 0, sizeof(struct request));
2613 rq.buf = radtlsget(client->ssl, 0);
2616 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2621 debug(DBG_ERR, "tlsserverrd: connection lost");
2622 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2624 pthread_mutex_lock(&client->replyq->mutex);
2625 pthread_cond_signal(&client->replyq->cond);
2626 pthread_mutex_unlock(&client->replyq->mutex);
2627 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2628 pthread_join(tlsserverwrth, NULL);
2629 removeclientrqs(client);
2630 debug(DBG_DBG, "tlsserverrd for %s exiting", client->conf->host);
2633 void *tlsservernew(void *arg) {
2635 struct sockaddr_storage from;
2636 size_t fromlen = sizeof(from);
2637 struct clsrvconf *conf;
2638 struct list_node *cur = NULL;
2641 unsigned long error;
2642 struct client *client;
2645 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
2646 debug(DBG_DBG, "tlsserverrd: getpeername failed, exiting");
2649 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2651 conf = find_conf('T', (struct sockaddr *)&from, clconfs, &cur);
2653 ssl = SSL_new(conf->ssl_ctx);
2656 if (SSL_accept(ssl) <= 0) {
2657 while ((error = ERR_get_error()))
2658 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2659 debug(DBG_ERR, "SSL_accept failed");
2662 cert = verifytlscert(ssl);
2668 if (verifyconfcert(cert, conf)) {
2670 client = addclient(conf);
2673 tlsserverrd(client);
2674 removeclient(client);
2676 debug(DBG_WARN, "Failed to create new client instance");
2679 conf = find_conf('T', (struct sockaddr *)&from, clconfs, &cur);
2681 debug(DBG_WARN, "ignoring request, no matching TLS client");
2687 shutdown(s, SHUT_RDWR);
2693 pthread_t tlsserverth;
2695 struct sockaddr_storage from;
2696 size_t fromlen = sizeof(from);
2697 struct clsrvconf *listenres;
2699 listenres = resolve_hostport('T', options.listentcp, DEFAULT_TLS_PORT);
2700 if ((s = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2701 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
2703 debug(DBG_WARN, "listening for incoming TCP on %s:%s", listenres->host ? listenres->host : "*", listenres->port);
2704 freeclsrvres(listenres);
2708 snew = accept(s, (struct sockaddr *)&from, &fromlen);
2710 debug(DBG_WARN, "accept failed");
2713 if (pthread_create(&tlsserverth, NULL, tlsservernew, (void *)&snew)) {
2714 debug(DBG_ERR, "tlslistener: pthread_create failed");
2715 shutdown(snew, SHUT_RDWR);
2719 pthread_detach(tlsserverth);
2724 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
2727 STACK_OF(X509_NAME) *calist;
2729 unsigned long error;
2731 if (!certfile || !certkeyfile)
2732 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2734 if (!cacertfile && !cacertpath)
2735 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2738 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2739 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2740 for (i = 0; i < CRYPTO_num_locks(); i++) {
2741 ssl_lock_count[i] = 0;
2742 pthread_mutex_init(&ssl_locks[i], NULL);
2744 CRYPTO_set_id_callback(ssl_thread_id);
2745 CRYPTO_set_locking_callback(ssl_locking_callback);
2747 SSL_load_error_strings();
2750 while (!RAND_status()) {
2751 time_t t = time(NULL);
2752 pid_t pid = getpid();
2753 RAND_seed((unsigned char *)&t, sizeof(time_t));
2754 RAND_seed((unsigned char *)&pid, sizeof(pid));
2757 ctx = SSL_CTX_new(TLSv1_method());
2759 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2760 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2762 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2763 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2764 !SSL_CTX_check_private_key(ctx) ||
2765 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2766 while ((error = ERR_get_error()))
2767 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2768 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2771 calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
2772 if (!cacertfile || calist) {
2775 calist = sk_X509_NAME_new_null();
2776 if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
2777 sk_X509_NAME_free(calist);
2783 while ((error = ERR_get_error()))
2784 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2785 debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
2787 SSL_CTX_set_client_CA_list(ctx, calist);
2789 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2790 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2792 new = malloc(sizeof(struct tls));
2793 if (!new || !list_push(tlsconfs, new))
2794 debugx(1, DBG_ERR, "malloc failed");
2796 memset(new, 0, sizeof(struct tls));
2797 new->name = stringcopy(value, 0);
2799 debugx(1, DBG_ERR, "malloc failed");
2801 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2804 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2805 struct list_node *entry;
2806 struct tls *t, *t1 = NULL, *t2 = NULL;
2808 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2809 t = (struct tls *)entry->data;
2810 if (!strcasecmp(t->name, alt1)) {
2814 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2824 struct list *addsrvconfs(char *value, char **names) {
2825 struct list *conflist;
2827 struct list_node *entry;
2828 struct clsrvconf *conf = NULL;
2830 if (!names || !*names)
2833 conflist = list_create();
2835 debug(DBG_ERR, "malloc failed");
2839 for (n = 0; names[n]; n++) {
2840 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2841 conf = (struct clsrvconf *)entry->data;
2842 if (!strcasecmp(names[n], conf->name))
2846 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2847 list_destroy(conflist);
2850 if (!list_push(conflist, conf)) {
2851 debug(DBG_ERR, "malloc failed");
2852 list_destroy(conflist);
2855 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2860 void freerealm(struct realm *realm) {
2864 free(realm->message);
2865 regfree(&realm->regex);
2866 pthread_mutex_destroy(&realm->subrealms_mutex);
2867 if (realm->subrealms)
2868 list_destroy(realm->subrealms);
2869 if (realm->srvconfs) {
2870 /* emptying list without freeing data */
2871 while (list_shift(realm->srvconfs));
2872 list_destroy(realm->srvconfs);
2874 if (realm->accsrvconfs) {
2875 /* emptying list without freeing data */
2876 while (list_shift(realm->accsrvconfs));
2877 list_destroy(realm->accsrvconfs);
2882 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message) {
2884 struct realm *realm;
2885 char *s, *regex = NULL;
2887 if (*value == '/') {
2888 /* regexp, remove optional trailing / if present */
2889 if (value[strlen(value) - 1] == '/')
2890 value[strlen(value) - 1] = '\0';
2892 /* not a regexp, let us make it one */
2893 if (*value == '*' && !value[1])
2894 regex = stringcopy(".*", 0);
2896 for (n = 0, s = value; *s;)
2899 regex = malloc(strlen(value) + n + 3);
2902 for (n = 1, s = value; *s; s++) {
2912 debug(DBG_ERR, "malloc failed");
2916 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2919 realm = malloc(sizeof(struct realm));
2921 debug(DBG_ERR, "malloc failed");
2924 memset(realm, 0, sizeof(struct realm));
2926 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
2927 debug(DBG_ERR, "mutex init failed");
2933 realm->name = stringcopy(value, 0);
2935 debug(DBG_ERR, "malloc failed");
2938 if (message && strlen(message) > 253) {
2939 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2942 realm->message = message;
2944 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
2945 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2949 if (servers && *servers) {
2950 realm->srvconfs = addsrvconfs(value, servers);
2951 if (!realm->srvconfs)
2955 if (accservers && *accservers) {
2956 realm->accsrvconfs = addsrvconfs(value, accservers);
2957 if (!realm->accsrvconfs)
2961 if (!list_push(realmlist, realm)) {
2962 debug(DBG_ERR, "malloc failed");
2963 pthread_mutex_destroy(&realm->subrealms_mutex);
2967 debug(DBG_DBG, "addrealm: added realm %s", value);
2977 for (n = 0; servers[n]; n++)
2982 for (n = 0; accservers[n]; n++)
2983 free(accservers[n]);
2989 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2990 struct clsrvconf *srvconf;
2991 struct realm *newrealm = NULL;
2992 char *realmname, *s;
2995 if (!conf->dynamiclookupcommand)
2998 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2999 realmname = strrchr(id, '@');
3005 for (s = realmname; *s; s++)
3006 if (*s != '.' && *s != '-' && !isalnum((int)*s))
3009 pthread_mutex_lock(&realm->subrealms_mutex);
3010 /* exit if we now already got a matching subrealm */
3011 if (id2realm(realm->subrealms, id))
3013 srvconf = malloc(sizeof(struct clsrvconf));
3015 debug(DBG_ERR, "malloc failed");
3019 if (!addserver(srvconf))
3022 if (!realm->subrealms)
3023 realm->subrealms = list_create();
3024 if (!realm->subrealms)
3026 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL);
3030 /* add server and accserver to newrealm */
3031 newrealm->srvconfs = list_create();
3032 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
3033 debug(DBG_ERR, "malloc failed");
3036 newrealm->accsrvconfs = list_create();
3037 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
3038 debug(DBG_ERR, "malloc failed");
3042 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
3044 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
3045 debug(DBG_ERR, "pthread_create failed");
3048 pthread_detach(clientth);
3053 list_removedata(realm->subrealms, newrealm);
3054 freerealm(newrealm);
3055 if (!list_first(realm->subrealms)) {
3056 list_destroy(realm->subrealms);
3057 realm->subrealms = NULL;
3060 freeserver(srvconf->servers, 1);
3062 debug(DBG_ERR, "failed to create dynamic server");
3065 pthread_mutex_unlock(&realm->subrealms_mutex);
3068 int dynamicconfig(struct server *server) {
3069 int ok, fd[2], status;
3071 struct clsrvconf *conf = server->conf;
3072 struct gconffile *cf = NULL;
3074 /* for now we only learn hostname/address */
3075 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
3078 debug(DBG_ERR, "dynamicconfig: pipe error");
3083 debug(DBG_ERR, "dynamicconfig: fork error");
3087 } else if (pid == 0) {
3090 if (fd[1] != STDOUT_FILENO) {
3091 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
3092 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
3095 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
3096 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
3100 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
3101 ok = getgenericconfig(&cf, NULL,
3102 "Server", CONF_CBK, confserver_cb, (void *)conf,
3107 if (waitpid(pid, &status, 0) < 0) {
3108 debug(DBG_ERR, "dynamicconfig: wait error");
3113 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
3121 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
3125 int addmatchcertattr(struct clsrvconf *conf) {
3129 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
3130 r = &conf->certcnregex;
3131 v = conf->matchcertattr + 4;
3132 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
3133 r = &conf->certuriregex;
3134 v = conf->matchcertattr + 20;
3139 /* regexp, remove optional trailing / if present */
3140 if (v[strlen(v) - 1] == '/')
3141 v[strlen(v) - 1] = '\0';
3145 *r = malloc(sizeof(regex_t));
3147 debug(DBG_ERR, "malloc failed");
3150 if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
3153 debug(DBG_ERR, "failed to compile regular expression %s", v);
3159 int addrewriteattr(struct clsrvconf *conf) {
3162 v = conf->rewriteattr + 11;
3163 if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
3165 /* regexp, remove optional trailing / if present */
3166 if (v[strlen(v) - 1] == '/')
3167 v[strlen(v) - 1] = '\0';
3175 conf->rewriteattrregex = malloc(sizeof(regex_t));
3176 if (!conf->rewriteattrregex) {
3177 debug(DBG_ERR, "malloc failed");
3181 conf->rewriteattrreplacement = stringcopy(w, 0);
3182 if (!conf->rewriteattrreplacement) {
3183 free(conf->rewriteattrregex);
3184 conf->rewriteattrregex = NULL;
3188 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
3189 free(conf->rewriteattrregex);
3190 conf->rewriteattrregex = NULL;
3191 free(conf->rewriteattrreplacement);
3192 conf->rewriteattrreplacement = NULL;
3193 debug(DBG_ERR, "failed to compile regular expression %s", v);
3200 /* should accept both names and numeric values, only numeric right now */
3201 uint8_t attrname2val(char *attrname) {
3204 val = atoi(attrname);
3205 return val > 0 && val < 256 ? val : 0;
3208 /* should accept both names and numeric values, only numeric right now */
3209 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
3212 *vendor = atoi(attrname);
3213 s = strchr(attrname, ':');
3218 *type = atoi(s + 1);
3219 return *type >= 0 && *type < 256;
3222 struct rewrite *getrewrite(char *alt1, char *alt2) {
3223 struct list_node *entry;
3224 struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
3226 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
3227 r = (struct rewriteconf *)entry->data;
3228 if (!strcasecmp(r->name, alt1)) {
3232 if (!r2 && alt2 && !strcasecmp(r->name, alt2))
3242 void addrewrite(char *value, char **attrs, char **vattrs) {
3243 struct rewriteconf *new;
3244 struct rewrite *rewrite = NULL;
3247 uint32_t *p, *va = NULL;
3251 for (; attrs[n]; n++);
3252 a = malloc((n + 1) * sizeof(uint8_t));
3254 debugx(1, DBG_ERR, "malloc failed");
3256 for (i = 0; i < n; i++) {
3257 if (!(a[i] = attrname2val(attrs[i])))
3258 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
3267 for (; vattrs[n]; n++);
3268 va = malloc((2 * n + 1) * sizeof(uint32_t));
3270 debugx(1, DBG_ERR, "malloc failed");
3272 for (p = va, i = 0; i < n; i++, p += 2) {
3273 if (!vattrname2val(vattrs[i], p, p + 1))
3274 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
3282 rewrite = malloc(sizeof(struct rewrite));
3284 debugx(1, DBG_ERR, "malloc failed");
3285 rewrite->removeattrs = a;
3286 rewrite->removevendorattrs = va;
3289 new = malloc(sizeof(struct rewriteconf));
3290 if (!new || !list_push(rewriteconfs, new))
3291 debugx(1, DBG_ERR, "malloc failed");
3293 memset(new, 0, sizeof(struct rewriteconf));
3294 new->name = stringcopy(value, 0);
3296 debugx(1, DBG_ERR, "malloc failed");
3298 new->rewrite = rewrite;
3299 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3302 void freeclsrvconf(struct clsrvconf *conf) {
3304 free(conf->conftype);
3309 free(conf->matchcertattr);
3310 if (conf->certcnregex)
3311 regfree(conf->certcnregex);
3312 if (conf->certuriregex)
3313 regfree(conf->certuriregex);
3314 free(conf->confrewrite);
3315 free(conf->rewriteattr);
3316 if (conf->rewriteattrregex)
3317 regfree(conf->rewriteattrregex);
3318 free(conf->rewriteattrreplacement);
3319 free(conf->dynamiclookupcommand);
3320 free(conf->rewrite);
3322 freeaddrinfo(conf->addrinfo);
3323 /* not touching ssl_ctx, clients and servers */
3327 int mergeconfstring(char **dst, char **src) {
3336 t = stringcopy(*dst, 0);
3338 debug(DBG_ERR, "malloc failed");
3346 /* assumes dst is a shallow copy */
3347 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3348 if (!mergeconfstring(&dst->name, &src->name) ||
3349 !mergeconfstring(&dst->conftype, &src->conftype) ||
3350 !mergeconfstring(&dst->host, &src->host) ||
3351 !mergeconfstring(&dst->port, &src->port) ||
3352 !mergeconfstring(&dst->secret, &src->secret) ||
3353 !mergeconfstring(&dst->tls, &src->tls) ||
3354 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3355 !mergeconfstring(&dst->confrewrite, &src->confrewrite) ||
3356 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3358 dst->statusserver = src->statusserver;
3359 dst->certnamecheck = src->certnamecheck;
3363 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3364 struct clsrvconf *conf;
3366 debug(DBG_DBG, "confclient_cb called for %s", block);
3368 conf = malloc(sizeof(struct clsrvconf));
3369 if (!conf || !list_push(clconfs, conf))
3370 debugx(1, DBG_ERR, "malloc failed");
3371 memset(conf, 0, sizeof(struct clsrvconf));
3372 conf->certnamecheck = 1;
3374 if (!getgenericconfig(cf, block,
3375 "type", CONF_STR, &conf->conftype,
3376 "host", CONF_STR, &conf->host,
3377 "secret", CONF_STR, &conf->secret,
3378 "tls", CONF_STR, &conf->tls,
3379 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3380 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3381 "rewrite", CONF_STR, &conf->confrewrite,
3382 "rewriteattribute", CONF_STR, &conf->rewriteattr,
3385 debugx(1, DBG_ERR, "configuration error");
3387 conf->name = stringcopy(val, 0);
3389 conf->host = stringcopy(val, 0);
3391 if (conf->conftype && !strcasecmp(conf->conftype, "udp")) {
3394 } else if (conf->conftype && !strcasecmp(conf->conftype, "tls")) {
3395 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultclient", "default");
3397 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3398 if (conf->matchcertattr && !addmatchcertattr(conf))
3399 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3403 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
3405 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
3407 if (conf->rewriteattr) {
3408 if (!addrewriteattr(conf))
3409 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3412 if (!resolvepeer(conf, 0))
3413 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3415 if (!conf->secret) {
3416 if (conf->type == 'U')
3417 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
3418 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
3423 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3424 switch (conf->type) {
3427 conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
3430 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultserver", "default");
3431 if (!conf->ssl_ctx) {
3432 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3435 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3436 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3440 conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
3444 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
3446 if (!conf->secret) {
3447 if (conf->type == 'U')
3448 debug(DBG_ERR, "error in block %s, secret must be specified for UDP", block);
3449 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
3450 if (!conf->secret) {
3451 debug(DBG_ERR, "malloc failed");
3456 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3457 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3463 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3464 struct clsrvconf *conf, *resconf;
3466 debug(DBG_DBG, "confserver_cb called for %s", block);
3468 conf = malloc(sizeof(struct clsrvconf));
3470 debug(DBG_ERR, "malloc failed");
3473 memset(conf, 0, sizeof(struct clsrvconf));
3474 resconf = (struct clsrvconf *)arg;
3476 conf->statusserver = resconf->statusserver;
3477 conf->certnamecheck = resconf->certnamecheck;
3479 conf->certnamecheck = 1;
3481 if (!getgenericconfig(cf, block,
3482 "type", CONF_STR, &conf->conftype,
3483 "host", CONF_STR, &conf->host,
3484 "port", CONF_STR, &conf->port,
3485 "secret", CONF_STR, &conf->secret,
3486 "tls", CONF_STR, &conf->tls,
3487 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3488 "rewrite", CONF_STR, &conf->confrewrite,
3489 "StatusServer", CONF_BLN, &conf->statusserver,
3490 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3491 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3494 debug(DBG_ERR, "configuration error");
3498 conf->name = stringcopy(val, 0);
3500 debug(DBG_ERR, "malloc failed");
3504 conf->host = stringcopy(val, 0);
3506 debug(DBG_ERR, "malloc failed");
3512 if (!mergesrvconf(resconf, conf))
3516 if (conf->dynamiclookupcommand) {
3517 free(conf->dynamiclookupcommand);
3518 conf->dynamiclookupcommand = NULL;
3522 if (conf->conftype && !strcasecmp(conf->conftype, "udp"))
3524 else if (conf->conftype && !strcasecmp(conf->conftype, "tls"))
3527 debug(DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
3531 if (resconf || !conf->dynamiclookupcommand) {
3532 if (!compileserverconfig(conf, block))
3539 switch (conf->type) {
3550 if (!list_push(srvconfs, conf)) {
3551 debug(DBG_ERR, "malloc failed");
3557 freeclsrvconf(conf);
3561 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3562 char **servers = NULL, **accservers = NULL, *msg = NULL;
3564 debug(DBG_DBG, "confrealm_cb called for %s", block);
3566 if (!getgenericconfig(cf, block,
3567 "server", CONF_MSTR, &servers,
3568 "accountingServer", CONF_MSTR, &accservers,
3569 "ReplyMessage", CONF_STR, &msg,
3572 debugx(1, DBG_ERR, "configuration error");
3574 addrealm(realms, val, servers, accservers, msg);
3578 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3579 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
3581 debug(DBG_DBG, "conftls_cb called for %s", block);
3583 if (!getgenericconfig(cf, block,
3584 "CACertificateFile", CONF_STR, &cacertfile,
3585 "CACertificatePath", CONF_STR, &cacertpath,
3586 "CertificateFile", CONF_STR, &certfile,
3587 "CertificateKeyFile", CONF_STR, &certkeyfile,
3588 "CertificateKeyPassword", CONF_STR, &certkeypwd,
3591 debugx(1, DBG_ERR, "configuration error");
3593 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
3602 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3603 char **attrs = NULL, **vattrs = NULL;
3605 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3607 if (!getgenericconfig(cf, block,
3608 "removeAttribute", CONF_MSTR, &attrs,
3609 "removeVendorAttribute", CONF_MSTR, &vattrs,
3612 debugx(1, DBG_ERR, "configuration error");
3613 addrewrite(val, attrs, vattrs);
3617 void getmainconfig(const char *configfile) {
3618 char *loglevel = NULL;
3619 struct gconffile *cfs;
3621 cfs = openconfigfile(configfile);
3622 memset(&options, 0, sizeof(options));
3624 clconfs = list_create();
3626 debugx(1, DBG_ERR, "malloc failed");
3628 srvconfs = list_create();
3630 debugx(1, DBG_ERR, "malloc failed");
3632 realms = list_create();
3634 debugx(1, DBG_ERR, "malloc failed");
3636 tlsconfs = list_create();
3638 debugx(1, DBG_ERR, "malloc failed");
3640 rewriteconfs = list_create();
3642 debugx(1, DBG_ERR, "malloc failed");
3644 if (!getgenericconfig(&cfs, NULL,
3645 "ListenUDP", CONF_STR, &options.listenudp,
3646 "ListenTCP", CONF_STR, &options.listentcp,
3647 "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
3648 "SourceUDP", CONF_STR, &options.sourceudp,
3649 "SourceTCP", CONF_STR, &options.sourcetcp,
3650 "LogLevel", CONF_STR, &loglevel,
3651 "LogDestination", CONF_STR, &options.logdestination,
3652 "LoopPrevention", CONF_BLN, &options.loopprevention,
3653 "Client", CONF_CBK, confclient_cb, NULL,
3654 "Server", CONF_CBK, confserver_cb, NULL,
3655 "Realm", CONF_CBK, confrealm_cb, NULL,
3656 "TLS", CONF_CBK, conftls_cb, NULL,
3657 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3660 debugx(1, DBG_ERR, "configuration error");
3663 if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
3664 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
3665 options.loglevel = *loglevel - '0';
3670 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3673 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3676 *configfile = optarg;
3679 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3680 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3681 *loglevel = *optarg - '0';
3690 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3695 if (!(argc - optind))
3699 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3703 int daemon(int a, int b) {
3711 for (i = 0; i < 3; i++) {
3713 open("/dev/null", O_RDWR);
3719 void *sighandler(void *arg) {
3724 sigemptyset(&sigset);
3725 sigaddset(&sigset, SIGPIPE);
3726 sigwait(&sigset, &sig);
3727 /* only get SIGPIPE right now, so could simplify below code */
3730 /* completely ignoring this */
3733 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3736 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3741 int main(int argc, char **argv) {
3742 pthread_t sigth, udpserverth, udpaccserverth, udpclient4rdth, udpclient6rdth;
3744 struct list_node *entry;
3745 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3746 char *configfile = NULL;
3747 struct clsrvconf *srvconf;
3749 debug_init("radsecproxy");
3750 debug_set_level(DEBUG_LEVEL);
3751 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3753 debug_set_level(loglevel);
3754 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3756 options.loglevel = loglevel;
3757 else if (options.loglevel)
3758 debug_set_level(options.loglevel);
3760 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3761 free(options.logdestination);
3763 if (!list_first(clconfs))
3764 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3765 if (!list_first(srvconfs))
3766 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
3767 if (!list_first(realms))
3768 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3771 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3773 if (!foreground && (daemon(0, 0) < 0))
3774 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3776 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3778 sigemptyset(&sigset);
3779 /* exit on all but SIGPIPE, ignore more? */
3780 sigaddset(&sigset, SIGPIPE);
3781 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3782 pthread_create(&sigth, NULL, sighandler, NULL);
3784 if (client_udp_count) {
3785 udp_server_replyq = newreplyq();
3786 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
3787 debugx(1, DBG_ERR, "pthread_create failed");
3788 if (options.listenaccudp)
3789 if (pthread_create(&udpaccserverth, NULL, udpaccserverrd, NULL))
3790 debugx(1, DBG_ERR, "pthread_create failed");
3793 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3794 srvconf = (struct clsrvconf *)entry->data;
3795 if (srvconf->dynamiclookupcommand)
3797 if (!addserver(srvconf))
3798 debugx(1, DBG_ERR, "failed to add server");
3799 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3800 (void *)(srvconf->servers)))
3801 debugx(1, DBG_ERR, "pthread_create failed");
3803 /* srcudpres no longer needed, while srctcpres is needed later */
3805 freeaddrinfo(srcudpres);
3808 if (udp_client4_sock >= 0)
3809 if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
3810 debugx(1, DBG_ERR, "pthread_create failed");
3811 if (udp_client6_sock >= 0)
3812 if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
3813 debugx(1, DBG_ERR, "pthread_create failed");
3815 if (client_tls_count)
3816 return tlslistener();
3818 /* just hang around doing nothing, anything to do here? */