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>
45 #include <arpa/inet.h>
49 #include <openssl/ssl.h>
50 #include <openssl/rand.h>
51 #include <openssl/err.h>
52 #include <openssl/md5.h>
53 #include <openssl/hmac.h>
54 #include <openssl/x509v3.h>
59 #include "radsecproxy.h"
61 static struct options options;
62 struct list *clconfs, *srvconfs, *realms, *tlsconfs, *rewriteconfs;
64 static int client_udp_count = 0;
65 static int client_tls_count = 0;
66 static int server_udp_count = 0;
67 static int server_tls_count = 0;
69 static struct addrinfo *srcudpres = NULL;
70 static struct addrinfo *srctcpres = NULL;
72 static struct replyq *udp_server_replyq = NULL;
73 static int udp_server_sock = -1;
74 static int udp_accserver_sock = -1;
75 static int udp_client4_sock = -1;
76 static int udp_client6_sock = -1;
77 static pthread_mutex_t *ssl_locks;
78 static long *ssl_lock_count;
82 /* minimum required declarations to avoid reordering code */
83 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
84 int dynamicconfig(struct server *server);
85 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
86 void freerealm(struct realm *realm);
87 void freeclsrvconf(struct clsrvconf *conf);
89 /* callbacks for making OpenSSL thread safe */
90 unsigned long ssl_thread_id() {
91 return (unsigned long)pthread_self();
94 void ssl_locking_callback(int mode, int type, const char *file, int line) {
95 if (mode & CRYPTO_LOCK) {
96 pthread_mutex_lock(&ssl_locks[type]);
97 ssl_lock_count[type]++;
99 pthread_mutex_unlock(&ssl_locks[type]);
102 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
103 int pwdlen = strlen(userdata);
104 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
106 memcpy(buf, userdata, pwdlen);
110 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
115 err_cert = X509_STORE_CTX_get_current_cert(ctx);
116 err = X509_STORE_CTX_get_error(ctx);
117 depth = X509_STORE_CTX_get_error_depth(ctx);
119 if (depth > MAX_CERT_DEPTH) {
121 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
122 X509_STORE_CTX_set_error(ctx, err);
126 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
127 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
130 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
131 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
132 debug(DBG_WARN, "\tIssuer=%s", buf);
134 case X509_V_ERR_CERT_NOT_YET_VALID:
135 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
136 debug(DBG_WARN, "\tCertificate not yet valid");
138 case X509_V_ERR_CERT_HAS_EXPIRED:
139 debug(DBG_WARN, "Certificate has expired");
141 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
142 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
147 printf("certificate verify returns %d\n", ok);
152 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
153 struct addrinfo hints, *addrinfo, *res;
157 slash = conf->host ? strchr(conf->host, '/') : NULL;
161 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
165 if (*s < '0' || *s > '9') {
166 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
169 plen = atoi(slash + 1);
170 if (plen < 0 || plen > 128) {
171 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
176 memset(&hints, 0, sizeof(hints));
177 hints.ai_socktype = (conf->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
178 hints.ai_family = AF_UNSPEC;
179 hints.ai_flags = ai_flags;
180 if (!conf->host && !conf->port) {
181 /* getaddrinfo() doesn't like host and port to be NULL */
182 if (getaddrinfo(conf->host, DEFAULT_UDP_PORT, &hints, &addrinfo)) {
183 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
186 for (res = addrinfo; res; res = res->ai_next) {
187 switch (res->ai_family) {
189 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
192 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
198 hints.ai_flags |= AI_NUMERICHOST;
199 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
200 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
205 switch (addrinfo->ai_family) {
208 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
209 freeaddrinfo(addrinfo);
216 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
217 freeaddrinfo(addrinfo);
220 conf->prefixlen = plen;
222 conf->prefixlen = 255;
225 freeaddrinfo(conf->addrinfo);
226 conf->addrinfo = addrinfo;
230 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
232 struct addrinfo *res;
234 for (res = addrinfo; res; res = res->ai_next) {
235 if (family != AF_UNSPEC && family != res->ai_family)
237 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
239 debug(DBG_WARN, "bindtoaddr: socket failed");
243 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
246 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
249 if (!bind(s, res->ai_addr, res->ai_addrlen))
251 debug(DBG_WARN, "bindtoaddr: bind failed");
257 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
262 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
266 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
268 debugx(1, DBG_ERR, "no ] matching initial [");
272 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
275 debugx(1, DBG_ERR, "missing host/address");
277 conf->host = stringcopy(field, p - field);
280 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
281 debugx(1, DBG_ERR, "unexpected character after ]");
284 /* port number or service name is specified */;
286 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
288 debugx(1, DBG_ERR, "syntax error, : but no following port");
289 conf->port = stringcopy(field, p - field);
291 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
295 struct clsrvconf *resolve_hostport(char type, char *lconf, char *default_port) {
296 struct clsrvconf *conf;
298 conf = malloc(sizeof(struct clsrvconf));
300 debugx(1, DBG_ERR, "malloc failed");
301 memset(conf, 0, sizeof(struct clsrvconf));
304 parsehostport(lconf, conf, default_port);
305 if (!strcmp(conf->host, "*")) {
310 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
311 if (!resolvepeer(conf, AI_PASSIVE))
312 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
316 void freeclsrvres(struct clsrvconf *res) {
320 freeaddrinfo(res->addrinfo);
324 int connecttcp(struct addrinfo *addrinfo) {
326 struct addrinfo *res;
329 for (res = addrinfo; res; res = res->ai_next) {
330 s = bindtoaddr(srctcpres, res->ai_family, 1, 1);
332 debug(DBG_WARN, "connecttoserver: socket failed");
335 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
337 debug(DBG_WARN, "connecttoserver: connect failed");
344 /* returns 1 if the len first bits are equal, else 0 */
345 int prefixmatch(void *a1, void *a2, uint8_t len) {
346 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
348 if (l && memcmp(a1, a2, l))
353 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
356 /* check if conf has matching address */
357 struct clsrvconf *checkconfaddr(char type, struct sockaddr *addr, struct clsrvconf *conf) {
358 struct sockaddr_in6 *sa6 = NULL;
359 struct in_addr *a4 = NULL;
360 struct addrinfo *res;
362 if (addr->sa_family == AF_INET6) {
363 sa6 = (struct sockaddr_in6 *)addr;
364 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
365 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
369 a4 = &((struct sockaddr_in *)addr)->sin_addr;
371 if (conf->type == type) {
372 if (conf->prefixlen == 255) {
373 for (res = conf->addrinfo; res; res = res->ai_next)
374 if ((a4 && res->ai_family == AF_INET &&
375 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
376 (sa6 && res->ai_family == AF_INET6 &&
377 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
380 res = conf->addrinfo;
382 ((a4 && res->ai_family == AF_INET &&
383 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
384 (sa6 && res->ai_family == AF_INET6 &&
385 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
392 /* returns next config with matching address, or NULL */
393 struct clsrvconf *find_conf(char type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
394 struct sockaddr_in6 *sa6 = NULL;
395 struct in_addr *a4 = NULL;
396 struct addrinfo *res;
397 struct list_node *entry;
398 struct clsrvconf *conf;
400 if (addr->sa_family == AF_INET6) {
401 sa6 = (struct sockaddr_in6 *)addr;
402 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
403 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
407 a4 = &((struct sockaddr_in *)addr)->sin_addr;
409 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
410 conf = (struct clsrvconf *)entry->data;
411 if (conf->type == type) {
412 if (conf->prefixlen == 255) {
413 for (res = conf->addrinfo; res; res = res->ai_next)
414 if ((a4 && res->ai_family == AF_INET &&
415 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
416 (sa6 && res->ai_family == AF_INET6 &&
417 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
423 res = conf->addrinfo;
425 ((a4 && res->ai_family == AF_INET &&
426 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
427 (sa6 && res->ai_family == AF_INET6 &&
428 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
439 struct replyq *newreplyq() {
440 struct replyq *replyq;
442 replyq = malloc(sizeof(struct replyq));
444 debugx(1, DBG_ERR, "malloc failed");
445 replyq->replies = list_create();
446 if (!replyq->replies)
447 debugx(1, DBG_ERR, "malloc failed");
448 pthread_mutex_init(&replyq->mutex, NULL);
449 pthread_cond_init(&replyq->cond, NULL);
453 struct client *addclient(struct clsrvconf *conf) {
454 struct client *new = malloc(sizeof(struct client));
457 debug(DBG_ERR, "malloc failed");
460 if (!conf->clients) {
461 conf->clients = list_create();
462 if (!conf->clients) {
463 debug(DBG_ERR, "malloc failed");
468 memset(new, 0, sizeof(struct client));
470 new->replyq = conf->type == 'T' ? newreplyq() : udp_server_replyq;
472 list_push(conf->clients, new);
476 void removeclient(struct client *client) {
477 struct list_node *entry;
479 if (!client || !client->conf->clients)
482 pthread_mutex_lock(&client->replyq->mutex);
483 for (entry = list_first(client->replyq->replies); entry; entry = list_next(entry))
484 free(((struct reply *)entry)->buf);
485 list_destroy(client->replyq->replies);
486 pthread_cond_destroy(&client->replyq->cond);
487 pthread_mutex_unlock(&client->replyq->mutex);
488 pthread_mutex_destroy(&client->replyq->mutex);
489 list_removedata(client->conf->clients, client);
493 void removeclientrqs(struct client *client) {
494 struct list_node *entry;
495 struct server *server;
499 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
500 server = ((struct clsrvconf *)entry->data)->servers;
501 pthread_mutex_lock(&server->newrq_mutex);
502 for (i = 0; i < MAX_REQUESTS; i++) {
503 rq = server->requests + i;
504 if (rq->from == client)
507 pthread_mutex_unlock(&server->newrq_mutex);
511 void freeserver(struct server *server, uint8_t destroymutex) {
515 free(server->requests);
516 free(server->dynamiclookuparg);
518 pthread_mutex_destroy(&server->lock);
519 pthread_cond_destroy(&server->newrq_cond);
520 pthread_mutex_destroy(&server->newrq_mutex);
525 int addserver(struct clsrvconf *conf) {
526 struct clsrvconf *res;
529 debug(DBG_ERR, "addserver: currently works with just one server per conf");
532 conf->servers = malloc(sizeof(struct server));
533 if (!conf->servers) {
534 debug(DBG_ERR, "malloc failed");
537 memset(conf->servers, 0, sizeof(struct server));
538 conf->servers->conf = conf;
540 if (conf->type == 'U') {
542 res = resolve_hostport('U', options.sourceudp, NULL);
543 srcudpres = res->addrinfo;
544 res->addrinfo = NULL;
547 switch (conf->addrinfo->ai_family) {
549 if (udp_client4_sock < 0) {
550 udp_client4_sock = bindtoaddr(srcudpres, AF_INET, 0, 1);
551 if (udp_client4_sock < 0)
552 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
554 conf->servers->sock = udp_client4_sock;
557 if (udp_client6_sock < 0) {
558 udp_client6_sock = bindtoaddr(srcudpres, AF_INET6, 0, 1);
559 if (udp_client6_sock < 0)
560 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
562 conf->servers->sock = udp_client6_sock;
565 debugx(1, DBG_ERR, "addserver: unsupported address family");
570 res = resolve_hostport('T', options.sourcetcp, NULL);
571 srctcpres = res->addrinfo;
572 res->addrinfo = NULL;
575 conf->servers->sock = -1;
578 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
579 if (!conf->servers->requests) {
580 debug(DBG_ERR, "malloc failed");
583 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
584 debug(DBG_ERR, "mutex init failed");
587 conf->servers->newrq = 0;
588 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
589 debug(DBG_ERR, "mutex init failed");
590 pthread_mutex_destroy(&conf->servers->lock);
593 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
594 debug(DBG_ERR, "mutex init failed");
595 pthread_mutex_destroy(&conf->servers->newrq_mutex);
596 pthread_mutex_destroy(&conf->servers->lock);
603 freeserver(conf->servers, 0);
604 conf->servers = NULL;
608 /* exactly one of client and server must be non-NULL */
609 /* should probably take peer list (client(s) or server(s)) as argument instead */
610 /* if *peer == NULL we return who we received from, else require it to be from peer */
611 /* return from in sa if not NULL */
612 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
614 unsigned char buf[65536], *rad;
615 struct sockaddr_storage from;
616 socklen_t fromlen = sizeof(from);
618 struct list_node *node;
621 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
623 debug(DBG_WARN, "radudpget: recv failed");
626 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
629 debug(DBG_WARN, "radudpget: packet too small");
635 debug(DBG_WARN, "radudpget: length too small");
640 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
644 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
648 p = checkconfaddr('U', (struct sockaddr *)&from, (*client)->conf);
650 p = find_conf('U', (struct sockaddr *)&from, clconfs, NULL);
653 p = checkconfaddr('U', (struct sockaddr *)&from, (*server)->conf);
655 p = find_conf('U', (struct sockaddr *)&from, srvconfs, NULL);
658 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
664 debug(DBG_ERR, "radudpget: malloc failed");
668 if (client && !*client) {
669 node = list_first(p->clients);
670 *client = node ? (struct client *)node->data : addclient(p);
675 } else if (server && !*server)
676 *server = p->servers;
680 memcpy(rad, buf, len);
686 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
687 int loc, i, l, n, r = 0;
690 STACK_OF(GENERAL_NAME) *alt;
693 debug(DBG_DBG, "subjectaltnameaddr");
695 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
699 ex = X509_get_ext(cert, loc);
700 alt = X509V3_EXT_d2i(ex);
704 n = sk_GENERAL_NAME_num(alt);
705 for (i = 0; i < n; i++) {
706 gn = sk_GENERAL_NAME_value(alt, i);
707 if (gn->type != GEN_IPADD)
710 v = (char *)ASN1_STRING_data(gn->d.ia5);
711 l = ASN1_STRING_length(gn->d.ia5);
712 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
713 && !memcmp(v, &addr, l)) {
718 GENERAL_NAMES_free(alt);
722 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
729 nm = X509_get_subject_name(cert);
732 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
735 e = X509_NAME_get_entry(nm, loc);
736 t = X509_NAME_ENTRY_get_data(e);
737 v = (char *) ASN1_STRING_data(t);
738 l = ASN1_STRING_length(t);
742 if (l == strlen(exact) && !strncasecmp(exact, v, l))
745 s = stringcopy((char *)v, l);
747 debug(DBG_ERR, "malloc failed");
750 if (regexec(regex, s, 0, NULL, 0)) {
761 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
762 int loc, i, l, n, r = 0;
765 STACK_OF(GENERAL_NAME) *alt;
768 debug(DBG_DBG, "subjectaltnameregexp");
770 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
774 ex = X509_get_ext(cert, loc);
775 alt = X509V3_EXT_d2i(ex);
779 n = sk_GENERAL_NAME_num(alt);
780 for (i = 0; i < n; i++) {
781 gn = sk_GENERAL_NAME_value(alt, i);
782 if (gn->type != type)
785 v = (char *)ASN1_STRING_data(gn->d.ia5);
786 l = ASN1_STRING_length(gn->d.ia5);
790 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
793 if (memcmp(v, exact, l))
796 s = stringcopy((char *)v, l);
798 debug(DBG_ERR, "malloc failed");
801 if (regexec(regex, s, 0, NULL, 0)) {
810 GENERAL_NAMES_free(alt);
814 X509 *verifytlscert(SSL *ssl) {
818 if (SSL_get_verify_result(ssl) != X509_V_OK) {
819 debug(DBG_ERR, "verifytlscert: basic validation failed");
820 while ((error = ERR_get_error()))
821 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
825 cert = SSL_get_peer_certificate(ssl);
827 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
831 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
833 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
834 struct in6_addr addr;
836 if (conf->certnamecheck && conf->prefixlen == 255) {
837 if (inet_pton(AF_INET, conf->host, &addr))
839 else if (inet_pton(AF_INET6, conf->host, &addr))
842 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
845 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
848 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
850 if (!cnregexp(cert, conf->host, NULL)) {
851 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
854 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
857 if (conf->certcnregex) {
858 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
859 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
862 debug(DBG_DBG, "verifyconfcert: CN matching regex");
864 if (conf->certuriregex) {
865 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
866 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
869 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
874 void tlsconnect(struct server *server, struct timeval *when, char *text) {
879 debug(DBG_DBG, "tlsconnect called from %s", text);
880 pthread_mutex_lock(&server->lock);
881 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
882 /* already reconnected, nothing to do */
883 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
884 pthread_mutex_unlock(&server->lock);
888 debug(DBG_DBG, "tlsconnect %s", text);
891 gettimeofday(&now, NULL);
892 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
893 if (server->connectionok) {
894 server->connectionok = 0;
896 } else if (elapsed < 1)
898 else if (elapsed < 60) {
899 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
901 } else if (elapsed < 100000) {
902 debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
905 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
906 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
907 if (server->sock >= 0)
909 if ((server->sock = connecttcp(server->conf->addrinfo)) < 0) {
910 debug(DBG_ERR, "tlsconnect: connecttcp failed");
914 SSL_free(server->ssl);
915 server->ssl = SSL_new(server->conf->ssl_ctx);
916 SSL_set_fd(server->ssl, server->sock);
917 if (SSL_connect(server->ssl) <= 0)
919 cert = verifytlscert(server->ssl);
922 if (verifyconfcert(cert, server->conf)) {
928 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
929 gettimeofday(&server->lastconnecttry, NULL);
930 pthread_mutex_unlock(&server->lock);
933 unsigned char *radtlsget(SSL *ssl) {
935 unsigned char buf[4], *rad;
938 for (total = 0; total < 4; total += cnt) {
939 cnt = SSL_read(ssl, buf + total, 4 - total);
941 debug(DBG_ERR, "radtlsget: connection lost");
942 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
943 /* remote end sent close_notify, send one back */
953 debug(DBG_ERR, "radtlsget: malloc failed");
958 for (; total < len; total += cnt) {
959 cnt = SSL_read(ssl, rad + total, len - total);
961 debug(DBG_ERR, "radtlsget: connection lost");
962 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
963 /* remote end sent close_notify, send one back */
975 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
978 debug(DBG_DBG, "radtlsget: got %d bytes", total);
982 int clientradputudp(struct server *server, unsigned char *rad) {
984 struct sockaddr_storage sa;
985 struct sockaddr *sap;
986 struct clsrvconf *conf = server->conf;
987 in_port_t *port = NULL;
991 if (*rad == RAD_Accounting_Request) {
992 sap = (struct sockaddr *)&sa;
993 memcpy(sap, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen);
995 sap = conf->addrinfo->ai_addr;
997 switch (sap->sa_family) {
999 port = &((struct sockaddr_in *)sap)->sin_port;
1002 port = &((struct sockaddr_in6 *)sap)->sin6_port;
1008 if (*rad == RAD_Accounting_Request)
1009 *port = htons(ntohs(*port) + 1);
1011 if (sendto(server->sock, rad, len, 0, sap, conf->addrinfo->ai_addrlen) >= 0) {
1012 debug(DBG_DBG, "clienradputudp: sent UDP of length %d to %s port %d", len, conf->host, ntohs(*port));
1016 debug(DBG_WARN, "clientradputudp: send failed");
1020 int clientradputtls(struct server *server, unsigned char *rad) {
1023 unsigned long error;
1024 struct timeval lastconnecttry;
1025 struct clsrvconf *conf = server->conf;
1028 lastconnecttry = server->lastconnecttry;
1029 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
1030 while ((error = ERR_get_error()))
1031 debug(DBG_ERR, "clientradputtls: TLS: %s", ERR_error_string(error, NULL));
1032 tlsconnect(server, &lastconnecttry, "clientradputtls");
1033 lastconnecttry = server->lastconnecttry;
1036 server->connectionok = 1;
1037 debug(DBG_DBG, "clientradputtls: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
1041 int clientradput(struct server *server, unsigned char *rad) {
1042 switch (server->conf->type) {
1044 return clientradputudp(server, rad);
1046 return clientradputtls(server, rad);
1051 int radsign(unsigned char *rad, unsigned char *sec) {
1052 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1053 static unsigned char first = 1;
1054 static EVP_MD_CTX mdctx;
1055 unsigned int md_len;
1058 pthread_mutex_lock(&lock);
1060 EVP_MD_CTX_init(&mdctx);
1064 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1065 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
1066 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1067 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
1069 pthread_mutex_unlock(&lock);
1073 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
1074 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1075 static unsigned char first = 1;
1076 static EVP_MD_CTX mdctx;
1077 unsigned char hash[EVP_MAX_MD_SIZE];
1081 pthread_mutex_lock(&lock);
1083 EVP_MD_CTX_init(&mdctx);
1089 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1090 EVP_DigestUpdate(&mdctx, rad, 4) &&
1091 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
1092 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
1093 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1094 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
1096 !memcmp(hash, rad + 4, 16));
1097 pthread_mutex_unlock(&lock);
1101 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
1102 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1103 static unsigned char first = 1;
1104 static HMAC_CTX hmacctx;
1105 unsigned int md_len;
1106 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
1108 pthread_mutex_lock(&lock);
1110 HMAC_CTX_init(&hmacctx);
1114 memcpy(auth, authattr, 16);
1115 memset(authattr, 0, 16);
1117 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1118 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1119 HMAC_Final(&hmacctx, hash, &md_len);
1120 memcpy(authattr, auth, 16);
1122 debug(DBG_WARN, "message auth computation failed");
1123 pthread_mutex_unlock(&lock);
1127 if (memcmp(auth, hash, 16)) {
1128 debug(DBG_WARN, "message authenticator, wrong value");
1129 pthread_mutex_unlock(&lock);
1133 pthread_mutex_unlock(&lock);
1137 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
1138 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1139 static unsigned char first = 1;
1140 static HMAC_CTX hmacctx;
1141 unsigned int md_len;
1146 pthread_mutex_lock(&lock);
1148 HMAC_CTX_init(&hmacctx);
1152 memset(authattrval, 0, 16);
1154 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1155 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1156 HMAC_Final(&hmacctx, authattrval, &md_len);
1158 debug(DBG_WARN, "message auth computation failed");
1159 pthread_mutex_unlock(&lock);
1163 pthread_mutex_unlock(&lock);
1167 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
1168 while (length > 1) {
1169 if (ATTRTYPE(attrs) == type)
1171 length -= ATTRLEN(attrs);
1172 attrs += ATTRLEN(attrs);
1177 void freerqdata(struct request *rq) {
1178 if (rq->origusername)
1179 free(rq->origusername);
1184 void sendrq(struct server *to, struct request *rq) {
1188 pthread_mutex_lock(&to->newrq_mutex);
1189 /* might simplify if only try nextid, might be ok */
1190 for (i = to->nextid; i < MAX_REQUESTS; i++)
1191 if (!to->requests[i].buf)
1193 if (i == MAX_REQUESTS) {
1194 for (i = 0; i < to->nextid; i++)
1195 if (!to->requests[i].buf)
1197 if (i == to->nextid) {
1198 debug(DBG_WARN, "No room in queue, dropping request");
1200 pthread_mutex_unlock(&to->newrq_mutex);
1205 rq->buf[1] = (char)i;
1207 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1208 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1210 pthread_mutex_unlock(&to->newrq_mutex);
1214 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1215 to->requests[i] = *rq;
1220 debug(DBG_DBG, "signalling client writer");
1221 pthread_cond_signal(&to->newrq_cond);
1223 pthread_mutex_unlock(&to->newrq_mutex);
1226 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
1227 struct reply *reply;
1230 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1232 debug(DBG_WARN, "sendreply: failed to sign message");
1236 reply = malloc(sizeof(struct reply));
1239 debug(DBG_ERR, "sendreply: malloc failed");
1242 memset(reply, 0, sizeof(struct reply));
1245 reply->tosa = *tosa;
1247 pthread_mutex_lock(&to->replyq->mutex);
1249 first = list_first(to->replyq->replies) == NULL;
1251 if (!list_push(to->replyq->replies, reply)) {
1252 pthread_mutex_unlock(&to->replyq->mutex);
1255 debug(DBG_ERR, "sendreply: malloc failed");
1260 debug(DBG_DBG, "signalling server writer");
1261 pthread_cond_signal(&to->replyq->cond);
1263 pthread_mutex_unlock(&to->replyq->mutex);
1266 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1267 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1268 static unsigned char first = 1;
1269 static EVP_MD_CTX mdctx;
1270 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1271 unsigned int md_len;
1272 uint8_t i, offset = 0, out[128];
1274 pthread_mutex_lock(&lock);
1276 EVP_MD_CTX_init(&mdctx);
1282 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1283 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1284 !EVP_DigestUpdate(&mdctx, input, 16) ||
1285 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1287 pthread_mutex_unlock(&lock);
1290 for (i = 0; i < 16; i++)
1291 out[offset + i] = hash[i] ^ in[offset + i];
1292 input = out + offset - 16;
1297 memcpy(in, out, len);
1298 pthread_mutex_unlock(&lock);
1302 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1303 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1304 static unsigned char first = 1;
1305 static EVP_MD_CTX mdctx;
1306 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1307 unsigned int md_len;
1308 uint8_t i, offset = 0, out[128];
1310 pthread_mutex_lock(&lock);
1312 EVP_MD_CTX_init(&mdctx);
1318 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1319 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1320 !EVP_DigestUpdate(&mdctx, input, 16) ||
1321 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1323 pthread_mutex_unlock(&lock);
1326 for (i = 0; i < 16; i++)
1327 out[offset + i] = hash[i] ^ in[offset + i];
1328 input = in + offset;
1333 memcpy(in, out, len);
1334 pthread_mutex_unlock(&lock);
1338 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1339 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1340 static unsigned char first = 1;
1341 static EVP_MD_CTX mdctx;
1342 unsigned char hash[EVP_MAX_MD_SIZE];
1343 unsigned int md_len;
1346 pthread_mutex_lock(&lock);
1348 EVP_MD_CTX_init(&mdctx);
1353 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1354 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1355 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1358 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1359 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1360 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1361 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1362 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1363 pthread_mutex_unlock(&lock);
1368 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1371 for (i = 0; i < 16; i++)
1374 for (offset = 16; offset < len; offset += 16) {
1376 printf("text + offset - 16 c(%d): ", offset / 16);
1377 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1379 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1380 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1381 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1382 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1384 pthread_mutex_unlock(&lock);
1388 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1391 for (i = 0; i < 16; i++)
1392 text[offset + i] ^= hash[i];
1396 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1399 pthread_mutex_unlock(&lock);
1403 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1404 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1405 static unsigned char first = 1;
1406 static EVP_MD_CTX mdctx;
1407 unsigned char hash[EVP_MAX_MD_SIZE];
1408 unsigned int md_len;
1412 pthread_mutex_lock(&lock);
1414 EVP_MD_CTX_init(&mdctx);
1419 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1420 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1421 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1424 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1425 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1426 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1427 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1428 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1429 pthread_mutex_unlock(&lock);
1434 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1437 for (i = 0; i < 16; i++)
1438 plain[i] = text[i] ^ hash[i];
1440 for (offset = 16; offset < len; offset += 16) {
1442 printf("text + offset - 16 c(%d): ", offset / 16);
1443 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1445 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1446 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1447 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1448 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1450 pthread_mutex_unlock(&lock);
1454 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1457 for (i = 0; i < 16; i++)
1458 plain[offset + i] = text[offset + i] ^ hash[i];
1461 memcpy(text, plain, len);
1463 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1466 pthread_mutex_unlock(&lock);
1470 struct realm *id2realm(struct list *realmlist, char *id) {
1471 struct list_node *entry;
1472 struct realm *realm, *subrealm = NULL;
1474 /* need to do locking for subrealms and check subrealm timers */
1475 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1476 realm = (struct realm *)entry->data;
1477 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1478 pthread_mutex_lock(&realm->subrealms_mutex);
1479 if (realm->subrealms)
1480 subrealm = id2realm(realm->subrealms, id);
1481 pthread_mutex_unlock(&realm->subrealms_mutex);
1482 return subrealm ? subrealm : realm;
1488 /* helper function, only used by removeserversubrealms() */
1489 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1490 struct list_node *entry;
1491 struct realm *realm;
1493 for (entry = list_first(realmlist); entry;) {
1494 realm = (struct realm *)entry->data;
1495 entry = list_next(entry);
1496 if (realm->srvconfs) {
1497 list_removedata(realm->srvconfs, srv);
1498 if (!list_first(realm->srvconfs)) {
1499 list_destroy(realm->srvconfs);
1500 realm->srvconfs = NULL;
1503 if (realm->accsrvconfs) {
1504 list_removedata(realm->accsrvconfs, srv);
1505 if (!list_first(realm->accsrvconfs)) {
1506 list_destroy(realm->accsrvconfs);
1507 realm->accsrvconfs = NULL;
1511 /* remove subrealm if no servers */
1512 if (!realm->srvconfs && !realm->accsrvconfs) {
1513 list_removedata(realmlist, realm);
1519 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1520 struct list_node *entry;
1521 struct realm *realm;
1523 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1524 realm = (struct realm *)entry->data;
1525 pthread_mutex_lock(&realm->subrealms_mutex);
1526 if (realm->subrealms) {
1527 _internal_removeserversubrealms(realm->subrealms, srv);
1528 if (!list_first(realm->subrealms)) {
1529 list_destroy(realm->subrealms);
1530 realm->subrealms = NULL;
1533 pthread_mutex_unlock(&realm->subrealms_mutex);
1537 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1538 struct request *rq = to->requests, *end;
1540 pthread_mutex_lock(&to->newrq_mutex);
1541 for (end = rq + MAX_REQUESTS; rq < end; rq++)
1542 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1544 pthread_mutex_unlock(&to->newrq_mutex);
1549 int attrvalidate(unsigned char *attrs, int length) {
1550 while (length > 1) {
1551 if (ATTRLEN(attrs) < 2) {
1552 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1555 length -= ATTRLEN(attrs);
1557 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1560 attrs += ATTRLEN(attrs);
1563 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1567 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1568 if (len < 16 || len > 128 || len % 16) {
1569 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1573 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1574 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1578 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1580 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1581 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1587 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1590 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1591 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1594 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1595 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1601 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1602 char *oldsecret, char *newsecret) {
1603 unsigned char *attr;
1605 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1606 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1607 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1613 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1617 for (; attrs[0]; attrs += 2)
1618 if (attrs[0] == vendor && attrs[1] == subattr)
1623 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1624 uint8_t alen, sublen, rmlen = 0;
1625 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1628 if (!removevendorattrs)
1631 while (*removevendorattrs && *removevendorattrs != vendor)
1632 removevendorattrs += 2;
1633 if (!*removevendorattrs)
1636 alen = ATTRLEN(attrs);
1638 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1639 /* remove entire vendor attribute */
1640 memmove(attrs, attrs + alen, length - alen);
1645 subattrs = ATTRVAL(attrs) + 4;
1647 if (!attrvalidate(subattrs, sublen)) {
1648 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1653 while (sublen > 1) {
1654 alen = ATTRLEN(subattrs);
1657 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1658 memmove(subattrs, subattrs + alen, length);
1664 ATTRLEN(attrs) -= rmlen;
1668 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1669 uint8_t *attrs, alen;
1670 uint16_t len, rmlen = 0;
1672 if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1675 len = RADLEN(buf) - 20;
1678 alen = ATTRLEN(attrs);
1680 if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1681 memmove(attrs, attrs + alen, len);
1683 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1684 rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1689 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1692 /* returns a pointer to the resized attribute value */
1693 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1694 uint8_t *attrs, *attr, vallen;
1698 len = RADLEN(*buf) - 20;
1701 attr = attrget(attrs, len, type);
1705 vallen = ATTRVALLEN(attr);
1706 if (vallen == newvallen)
1709 len += newvallen - vallen;
1710 if (newvallen > vallen) {
1711 new = realloc(*buf, len + 20);
1713 debug(DBG_ERR, "resizeattr: malloc failed");
1722 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1723 attr[1] = newvallen + 2;
1724 ((uint16_t *)*buf)[1] = htons(len + 20);
1728 int rewriteusername(struct request *rq, char *in) {
1729 size_t nmatch = 10, reslen = 0, start = 0;
1730 regmatch_t pmatch[10], *pfield;
1732 unsigned char *result;
1733 char *out = rq->from->conf->rewriteattrreplacement;
1735 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1736 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1740 rq->origusername = stringcopy(in, 0);
1741 if (!rq->origusername)
1744 for (i = start; out[i]; i++) {
1745 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1746 pfield = &pmatch[out[i + 1] - '0'];
1747 if (pfield->rm_so >= 0) {
1748 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1754 reslen += i - start;
1756 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1762 for (i = start; out[i]; i++) {
1763 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1764 pfield = &pmatch[out[i + 1] - '0'];
1765 if (pfield->rm_so >= 0) {
1766 memcpy(result + reslen, out + start, i - start);
1767 reslen += i - start;
1768 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1769 reslen += pfield->rm_eo - pfield->rm_so;
1776 memcpy(result + reslen, out + start, i - start);
1777 reslen += i - start;
1778 memcpy(in, result, reslen);
1783 const char *radmsgtype2string(uint8_t code) {
1784 static const char *rad_msg_names[] = {
1785 "", "Access-Request", "Access-Accept", "Access-Reject",
1786 "Accounting-Request", "Accounting-Response", "", "",
1787 "", "", "", "Access-Challenge",
1788 "Status-Server", "Status-Client"
1790 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1793 void char2hex(char *h, unsigned char c) {
1794 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1795 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1796 h[0] = hexdigits[c / 16];
1797 h[1] = hexdigits[c % 16];
1801 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
1805 if (!attr || len == 1) {
1810 l = ATTRVALLEN(attr);
1811 s = (char *)ATTRVAL(attr);
1814 for (i = 0; i < l; i++) {
1815 if (s[i] > 31 && s[i] < 127) {
1817 if (d - ascii == len - 1)
1820 if (d - ascii > len - 4)
1825 if (d - ascii == len - 1)
1833 void acclog(unsigned char *attrs, int length, char *host) {
1834 unsigned char *attr;
1837 attr = attrget(attrs, length, RAD_Attr_User_Name);
1839 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1842 radattr2ascii(username, sizeof(username), attr);
1843 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1846 void respondaccounting(struct request *rq) {
1847 unsigned char *resp;
1851 debug(DBG_ERR, "respondstatusserver: malloc failed");
1854 memcpy(resp, rq->buf, 20);
1855 resp[0] = RAD_Accounting_Response;
1858 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1859 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1862 void respondstatusserver(struct request *rq) {
1863 unsigned char *resp;
1867 debug(DBG_ERR, "respondstatusserver: malloc failed");
1870 memcpy(resp, rq->buf, 20);
1871 resp[0] = RAD_Access_Accept;
1874 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1875 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1878 void respondreject(struct request *rq, char *message) {
1879 unsigned char *resp;
1882 if (message && *message)
1883 len += 2 + strlen(message);
1887 debug(DBG_ERR, "respondreject: malloc failed");
1890 memcpy(resp, rq->buf, 20);
1891 resp[0] = RAD_Access_Reject;
1892 *(uint16_t *)(resp + 2) = htons(len);
1893 if (message && *message) {
1894 resp[20] = RAD_Attr_Reply_Message;
1895 resp[21] = len - 20;
1896 memcpy(resp + 22, message, len - 22);
1898 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1901 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1902 struct list_node *entry;
1903 struct clsrvconf *server, *best = NULL, *first = NULL;
1905 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1906 server = (struct clsrvconf *)entry->data;
1907 if (!server->servers)
1911 if (!server->servers->connectionok)
1913 if (!server->servers->loststatsrv)
1919 if (server->servers->loststatsrv < best->servers->loststatsrv)
1922 return best ? best : first;
1925 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
1926 struct clsrvconf *srvconf;
1928 *realm = id2realm(realms, id);
1931 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1932 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1935 if (!acc && !srvconf->servers)
1936 adddynamicrealmserver(*realm, srvconf, id);
1937 return srvconf->servers;
1940 void radsrv(struct request *rq) {
1941 uint8_t code, id, *auth, *attrs, *attr;
1943 struct server *to = NULL;
1944 char username[254], userascii[760];
1945 unsigned char newauth[16];
1946 struct realm *realm = NULL;
1948 code = *(uint8_t *)rq->buf;
1949 id = *(uint8_t *)(rq->buf + 1);
1950 len = RADLEN(rq->buf);
1951 auth = (uint8_t *)(rq->buf + 4);
1953 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1955 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1956 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1961 attrs = rq->buf + 20;
1963 if (!attrvalidate(attrs, len)) {
1964 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1968 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1969 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
1970 debug(DBG_WARN, "radsrv: message authentication failed");
1974 if (code == RAD_Status_Server) {
1975 respondstatusserver(rq);
1979 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1981 if (rq->from->conf->rewrite) {
1982 dorewrite(rq->buf, rq->from->conf->rewrite);
1983 len = RADLEN(rq->buf) - 20;
1986 attr = attrget(attrs, len, RAD_Attr_User_Name);
1988 if (code == RAD_Accounting_Request) {
1989 acclog(attrs, len, rq->from->conf->host);
1990 respondaccounting(rq);
1992 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1995 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1996 username[ATTRVALLEN(attr)] = '\0';
1997 radattr2ascii(userascii, sizeof(userascii), attr);
1999 if (rq->from->conf->rewriteattrregex) {
2000 if (!rewriteusername(rq, username)) {
2001 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
2004 len = RADLEN(rq->buf) - 20;
2005 auth = (uint8_t *)(rq->buf + 4);
2006 attrs = rq->buf + 20;
2009 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
2011 to = findserver(&realm, username, code == RAD_Accounting_Request);
2013 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
2017 if (realm->message && code == RAD_Access_Request) {
2018 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
2019 respondreject(rq, realm->message);
2024 if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
2025 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
2026 rq->from->conf->name, to->conf->name);
2030 if (rqinqueue(to, rq->from, id, code)) {
2031 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
2032 radmsgtype2string(code), rq->from->conf->host, id);
2036 if (!RAND_bytes(newauth, 16)) {
2037 debug(DBG_WARN, "radsrv: failed to generate random auth");
2042 printfchars(NULL, "auth", "%02x ", auth, 16);
2045 attr = attrget(attrs, len, RAD_Attr_User_Password);
2047 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
2048 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2052 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
2054 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
2055 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2060 memcpy(rq->origauth, auth, 16);
2061 memcpy(auth, newauth, 16);
2069 int replyh(struct server *server, unsigned char *buf) {
2070 struct client *from;
2073 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
2074 struct sockaddr_storage fromsa;
2075 char tmp[760], stationid[760];
2077 server->connectionok = 1;
2078 server->loststatsrv = 0;
2080 i = buf[1]; /* i is the id */
2082 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
2083 && *buf != RAD_Accounting_Response) {
2084 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
2087 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
2089 rq = server->requests + i;
2091 pthread_mutex_lock(&server->newrq_mutex);
2092 if (!rq->buf || !rq->tries) {
2093 pthread_mutex_unlock(&server->newrq_mutex);
2094 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
2099 pthread_mutex_unlock(&server->newrq_mutex);
2100 debug(DBG_INFO, "replyh: already received, ignoring reply");
2104 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
2105 pthread_mutex_unlock(&server->newrq_mutex);
2106 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
2110 len = RADLEN(buf) - 20;
2113 if (!attrvalidate(attrs, len)) {
2114 pthread_mutex_unlock(&server->newrq_mutex);
2115 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
2119 /* Message Authenticator */
2120 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2122 if (ATTRVALLEN(messageauth) != 16) {
2123 pthread_mutex_unlock(&server->newrq_mutex);
2124 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
2127 memcpy(tmp, buf + 4, 16);
2128 memcpy(buf + 4, rq->buf + 4, 16);
2129 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
2130 pthread_mutex_unlock(&server->newrq_mutex);
2131 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
2134 memcpy(buf + 4, tmp, 16);
2135 debug(DBG_DBG, "replyh: message auth ok");
2138 if (*rq->buf == RAD_Status_Server) {
2140 pthread_mutex_unlock(&server->newrq_mutex);
2141 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2147 pthread_mutex_unlock(&server->newrq_mutex);
2148 debug(DBG_INFO, "replyh: client gone, ignoring reply");
2152 if (server->conf->rewrite) {
2153 dorewrite(buf, server->conf->rewrite);
2154 len = RADLEN(buf) - 20;
2158 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2159 if (ATTRVALLEN(attr) <= 4)
2162 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
2165 sublen = ATTRVALLEN(attr) - 4;
2166 subattrs = ATTRVAL(attr) + 4;
2167 if (!attrvalidate(subattrs, sublen) ||
2168 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2169 rq, server->conf->secret, from->conf->secret) ||
2170 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2171 rq, server->conf->secret, from->conf->secret))
2175 pthread_mutex_unlock(&server->newrq_mutex);
2176 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2180 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2181 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2183 radattr2ascii(tmp, sizeof(tmp), attr);
2184 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2186 radattr2ascii(stationid, sizeof(stationid), attr);
2187 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2188 radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2190 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2194 buf[1] = (char)rq->origid;
2195 memcpy(buf + 4, rq->origauth, 16);
2197 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2200 if (rq->origusername) {
2201 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2203 pthread_mutex_unlock(&server->newrq_mutex);
2204 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2207 memcpy(username, rq->origusername, strlen(rq->origusername));
2208 len = RADLEN(buf) - 20;
2211 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2215 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2216 pthread_mutex_unlock(&server->newrq_mutex);
2217 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2220 debug(DBG_DBG, "replyh: computed messageauthattr");
2223 if (from->conf->type == 'U')
2224 fromsa = rq->fromsa;
2225 /* once we set received = 1, rq may be reused */
2228 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2229 sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
2230 pthread_mutex_unlock(&server->newrq_mutex);
2234 void *udpclientrd(void *arg) {
2235 struct server *server;
2237 int *s = (int *)arg;
2241 buf = radudpget(*s, NULL, &server, NULL);
2242 if (!replyh(server, buf))
2247 void *tlsclientrd(void *arg) {
2248 struct server *server = (struct server *)arg;
2250 struct timeval lastconnecttry;
2253 /* yes, lastconnecttry is really necessary */
2254 lastconnecttry = server->lastconnecttry;
2255 buf = radtlsget(server->ssl);
2257 tlsconnect(server, &lastconnecttry, "clientrd");
2261 if (!replyh(server, buf))
2266 /* code for removing state not finished */
2267 void *clientwr(void *arg) {
2268 struct server *server = (struct server *)arg;
2270 pthread_t tlsclientrdth;
2273 struct timeval now, lastsend;
2274 struct timespec timeout;
2275 struct request statsrvrq;
2276 unsigned char statsrvbuf[38];
2277 struct clsrvconf *conf;
2279 conf = server->conf;
2281 if (server->dynamiclookuparg && !dynamicconfig(server))
2284 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2285 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2289 memset(&timeout, 0, sizeof(struct timespec));
2291 if (conf->statusserver) {
2292 memset(&statsrvrq, 0, sizeof(struct request));
2293 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2294 statsrvbuf[0] = RAD_Status_Server;
2296 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2297 statsrvbuf[21] = 18;
2298 gettimeofday(&lastsend, NULL);
2301 if (conf->type == 'U') {
2302 server->connectionok = 1;
2304 tlsconnect(server, NULL, "new client");
2305 server->connectionok = 1;
2306 if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server)) {
2307 debug(DBG_ERR, "clientwr: pthread_create failed");
2313 pthread_mutex_lock(&server->newrq_mutex);
2314 if (!server->newrq) {
2315 gettimeofday(&now, NULL);
2316 if (conf->statusserver) {
2317 /* random 0-7 seconds */
2318 RAND_bytes(&rnd, 1);
2320 if (!timeout.tv_sec || timeout.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
2321 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
2323 if (timeout.tv_sec) {
2324 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2325 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2328 debug(DBG_DBG, "clientwr: waiting for new request");
2329 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
2332 if (server->newrq) {
2333 debug(DBG_DBG, "clientwr: got new request");
2336 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2337 pthread_mutex_unlock(&server->newrq_mutex);
2339 for (i = 0; i < MAX_REQUESTS; i++) {
2340 pthread_mutex_lock(&server->newrq_mutex);
2341 while (i < MAX_REQUESTS && !server->requests[i].buf)
2343 if (i == MAX_REQUESTS) {
2344 pthread_mutex_unlock(&server->newrq_mutex);
2347 rq = server->requests + i;
2350 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2352 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2354 /* setting this to NULL means that it can be reused */
2357 pthread_mutex_unlock(&server->newrq_mutex);
2361 gettimeofday(&now, NULL);
2362 if (now.tv_sec < rq->expiry.tv_sec) {
2363 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2364 timeout.tv_sec = rq->expiry.tv_sec;
2365 pthread_mutex_unlock(&server->newrq_mutex);
2369 if (rq->tries == (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
2370 ? 1 : REQUEST_RETRIES)) {
2371 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2372 if (*rq->buf == RAD_Status_Server) {
2373 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2374 if (server->loststatsrv < 255)
2375 server->loststatsrv++;
2378 /* setting this to NULL means that it can be reused */
2380 pthread_mutex_unlock(&server->newrq_mutex);
2383 pthread_mutex_unlock(&server->newrq_mutex);
2385 rq->expiry.tv_sec = now.tv_sec +
2386 (*rq->buf == RAD_Status_Server || conf->type == 'T'
2387 ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
2388 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2389 timeout.tv_sec = rq->expiry.tv_sec;
2391 clientradput(server, server->requests[i].buf);
2392 gettimeofday(&lastsend, NULL);
2394 if (conf->statusserver) {
2395 gettimeofday(&now, NULL);
2396 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
2397 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2398 debug(DBG_WARN, "clientwr: failed to generate random auth");
2401 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2402 if (!statsrvrq.buf) {
2403 debug(DBG_ERR, "clientwr: malloc failed");
2406 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2407 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2408 lastsend.tv_sec = now.tv_sec;
2409 sendrq(server, &statsrvrq);
2414 if (server->dynamiclookuparg) {
2415 removeserversubrealms(realms, conf);
2416 freeclsrvconf(conf);
2418 freeserver(server, 1);
2422 void *udpserverwr(void *arg) {
2423 struct replyq *replyq = udp_server_replyq;
2424 struct reply *reply;
2427 pthread_mutex_lock(&replyq->mutex);
2428 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2429 debug(DBG_DBG, "udp server writer, waiting for signal");
2430 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2431 debug(DBG_DBG, "udp server writer, got signal");
2433 pthread_mutex_unlock(&replyq->mutex);
2435 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
2436 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2437 debug(DBG_WARN, "sendudp: send failed");
2443 void *udpserverrd(void *arg) {
2445 pthread_t udpserverwrth;
2446 struct clsrvconf *listenres;
2448 listenres = resolve_hostport('U', options.listenudp, DEFAULT_UDP_PORT);
2449 if ((udp_server_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2450 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2452 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
2453 listenres->host ? listenres->host : "*", listenres->port);
2454 freeclsrvres(listenres);
2456 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
2457 debugx(1, DBG_ERR, "pthread_create failed");
2460 memset(&rq, 0, sizeof(struct request));
2461 rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
2466 void *udpaccserverrd(void *arg) {
2468 struct clsrvconf *listenres;
2470 listenres = resolve_hostport('U', options.listenaccudp, DEFAULT_UDP_PORT);
2471 if ((udp_accserver_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2472 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2474 debug(DBG_WARN, "udpaccserverrd: listening for UDP on %s:%s",
2475 listenres->host ? listenres->host : "*", listenres->port);
2476 freeclsrvres(listenres);
2479 memset(&rq, 0, sizeof(struct request));
2480 rq.buf = radudpget(udp_accserver_sock, &rq.from, NULL, &rq.fromsa);
2481 if (*(uint8_t *)rq.buf == RAD_Accounting_Request) {
2485 debug(DBG_INFO, "udpaccserverrd: got something other than accounting-request, ignoring");
2490 void *tlsserverwr(void *arg) {
2492 unsigned long error;
2493 struct client *client = (struct client *)arg;
2494 struct replyq *replyq;
2495 struct reply *reply;
2497 debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
2498 replyq = client->replyq;
2500 pthread_mutex_lock(&replyq->mutex);
2501 while (!list_first(replyq->replies)) {
2503 debug(DBG_DBG, "tls server writer, waiting for signal");
2504 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2505 debug(DBG_DBG, "tls server writer, got signal");
2508 /* ssl might have changed while waiting */
2509 pthread_mutex_unlock(&replyq->mutex);
2510 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2514 reply = (struct reply *)list_shift(replyq->replies);
2515 pthread_mutex_unlock(&replyq->mutex);
2516 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2518 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
2519 cnt, RADLEN(reply->buf));
2521 while ((error = ERR_get_error()))
2522 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2528 void tlsserverrd(struct client *client) {
2530 pthread_t tlsserverwrth;
2532 debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2534 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2535 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2540 memset(&rq, 0, sizeof(struct request));
2541 rq.buf = radtlsget(client->ssl);
2544 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2549 debug(DBG_ERR, "tlsserverrd: connection lost");
2550 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2552 pthread_mutex_lock(&client->replyq->mutex);
2553 pthread_cond_signal(&client->replyq->cond);
2554 pthread_mutex_unlock(&client->replyq->mutex);
2555 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2556 pthread_join(tlsserverwrth, NULL);
2557 removeclientrqs(client);
2558 debug(DBG_DBG, "tlsserverrd for %s exiting", client->conf->host);
2561 void *tlsservernew(void *arg) {
2563 struct sockaddr_storage from;
2564 size_t fromlen = sizeof(from);
2565 struct clsrvconf *conf;
2566 struct list_node *cur = NULL;
2569 unsigned long error;
2570 struct client *client;
2573 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
2574 debug(DBG_DBG, "tlsserverrd: getpeername failed, exiting");
2577 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2579 conf = find_conf('T', (struct sockaddr *)&from, clconfs, &cur);
2581 ssl = SSL_new(conf->ssl_ctx);
2584 if (SSL_accept(ssl) <= 0) {
2585 while ((error = ERR_get_error()))
2586 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2587 debug(DBG_ERR, "SSL_accept failed");
2590 cert = verifytlscert(ssl);
2596 if (verifyconfcert(cert, conf)) {
2598 client = addclient(conf);
2601 tlsserverrd(client);
2602 removeclient(client);
2604 debug(DBG_WARN, "Failed to create new client instance");
2607 conf = find_conf('T', (struct sockaddr *)&from, clconfs, &cur);
2609 debug(DBG_WARN, "ignoring request, no matching TLS client");
2615 shutdown(s, SHUT_RDWR);
2621 pthread_t tlsserverth;
2623 struct sockaddr_storage from;
2624 size_t fromlen = sizeof(from);
2625 struct clsrvconf *listenres;
2627 listenres = resolve_hostport('T', options.listentcp, DEFAULT_TLS_PORT);
2628 if ((s = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2629 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
2631 debug(DBG_WARN, "listening for incoming TCP on %s:%s", listenres->host ? listenres->host : "*", listenres->port);
2632 freeclsrvres(listenres);
2636 snew = accept(s, (struct sockaddr *)&from, &fromlen);
2638 debug(DBG_WARN, "accept failed");
2641 if (pthread_create(&tlsserverth, NULL, tlsservernew, (void *)&snew)) {
2642 debug(DBG_ERR, "tlslistener: pthread_create failed");
2643 shutdown(snew, SHUT_RDWR);
2647 pthread_detach(tlsserverth);
2652 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
2655 STACK_OF(X509_NAME) *calist;
2657 unsigned long error;
2659 if (!certfile || !certkeyfile)
2660 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2662 if (!cacertfile && !cacertpath)
2663 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2666 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2667 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2668 for (i = 0; i < CRYPTO_num_locks(); i++) {
2669 ssl_lock_count[i] = 0;
2670 pthread_mutex_init(&ssl_locks[i], NULL);
2672 CRYPTO_set_id_callback(ssl_thread_id);
2673 CRYPTO_set_locking_callback(ssl_locking_callback);
2675 SSL_load_error_strings();
2678 while (!RAND_status()) {
2679 time_t t = time(NULL);
2680 pid_t pid = getpid();
2681 RAND_seed((unsigned char *)&t, sizeof(time_t));
2682 RAND_seed((unsigned char *)&pid, sizeof(pid));
2685 ctx = SSL_CTX_new(TLSv1_method());
2687 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2688 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2690 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2691 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2692 !SSL_CTX_check_private_key(ctx) ||
2693 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2694 while ((error = ERR_get_error()))
2695 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2696 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2699 calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
2700 if (!cacertfile || calist) {
2703 calist = sk_X509_NAME_new_null();
2704 if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
2705 sk_X509_NAME_free(calist);
2711 while ((error = ERR_get_error()))
2712 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2713 debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
2715 SSL_CTX_set_client_CA_list(ctx, calist);
2717 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2718 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2720 new = malloc(sizeof(struct tls));
2721 if (!new || !list_push(tlsconfs, new))
2722 debugx(1, DBG_ERR, "malloc failed");
2724 memset(new, 0, sizeof(struct tls));
2725 new->name = stringcopy(value, 0);
2727 debugx(1, DBG_ERR, "malloc failed");
2729 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2732 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2733 struct list_node *entry;
2734 struct tls *t, *t1 = NULL, *t2 = NULL;
2736 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2737 t = (struct tls *)entry->data;
2738 if (!strcasecmp(t->name, alt1)) {
2742 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2752 struct list *addsrvconfs(char *value, char **names) {
2753 struct list *conflist;
2755 struct list_node *entry;
2756 struct clsrvconf *conf;
2758 if (!names || !*names)
2761 conflist = list_create();
2763 debug(DBG_ERR, "malloc failed");
2767 for (n = 0; names[n]; n++) {
2768 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2769 conf = (struct clsrvconf *)entry->data;
2770 if (!strcasecmp(names[n], conf->name))
2774 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2775 list_destroy(conflist);
2778 if (!list_push(conflist, conf)) {
2779 debug(DBG_ERR, "malloc failed");
2780 list_destroy(conflist);
2783 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2788 void freerealm(struct realm *realm) {
2792 free(realm->message);
2793 regfree(&realm->regex);
2794 pthread_mutex_destroy(&realm->subrealms_mutex);
2795 if (realm->subrealms)
2796 list_destroy(realm->subrealms);
2797 if (realm->srvconfs) {
2798 /* emptying list without freeing data */
2799 while (list_shift(realm->srvconfs));
2800 list_destroy(realm->srvconfs);
2802 if (realm->accsrvconfs) {
2803 /* emptying list without freeing data */
2804 while (list_shift(realm->accsrvconfs));
2805 list_destroy(realm->accsrvconfs);
2810 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message) {
2812 struct realm *realm;
2813 char *s, *regex = NULL;
2815 if (*value == '/') {
2816 /* regexp, remove optional trailing / if present */
2817 if (value[strlen(value) - 1] == '/')
2818 value[strlen(value) - 1] = '\0';
2820 /* not a regexp, let us make it one */
2821 if (*value == '*' && !value[1])
2822 regex = stringcopy(".*", 0);
2824 for (n = 0, s = value; *s;)
2827 regex = malloc(strlen(value) + n + 3);
2830 for (n = 1, s = value; *s; s++) {
2840 debug(DBG_ERR, "malloc failed");
2844 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2847 realm = malloc(sizeof(struct realm));
2849 debug(DBG_ERR, "malloc failed");
2852 memset(realm, 0, sizeof(struct realm));
2854 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
2855 debug(DBG_ERR, "mutex init failed");
2861 realm->name = stringcopy(value, 0);
2863 debug(DBG_ERR, "malloc failed");
2866 if (message && strlen(message) > 253) {
2867 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2870 realm->message = message;
2872 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
2873 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2877 if (servers && *servers) {
2878 realm->srvconfs = addsrvconfs(value, servers);
2879 if (!realm->srvconfs)
2883 if (accservers && *accservers) {
2884 realm->accsrvconfs = addsrvconfs(value, accservers);
2885 if (!realm->accsrvconfs)
2889 if (!list_push(realmlist, realm)) {
2890 debug(DBG_ERR, "malloc failed");
2891 pthread_mutex_destroy(&realm->subrealms_mutex);
2895 debug(DBG_DBG, "addrealm: added realm %s", value);
2905 for (n = 0; servers[n]; n++)
2910 for (n = 0; accservers[n]; n++)
2911 free(accservers[n]);
2917 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2918 struct clsrvconf *srvconf;
2919 struct realm *newrealm = NULL;
2920 char *realmname, *s;
2923 if (!conf->dynamiclookupcommand)
2926 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2927 realmname = strrchr(id, '@');
2933 for (s = realmname; *s; s++)
2934 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2937 pthread_mutex_lock(&realm->subrealms_mutex);
2938 /* exit if we now already got a matching subrealm */
2939 if (id2realm(realm->subrealms, id))
2941 srvconf = malloc(sizeof(struct clsrvconf));
2943 debug(DBG_ERR, "malloc failed");
2947 if (!addserver(srvconf))
2950 if (!realm->subrealms)
2951 realm->subrealms = list_create();
2952 if (!realm->subrealms)
2954 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL);
2958 /* add server and accserver to newrealm */
2959 newrealm->srvconfs = list_create();
2960 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2961 debug(DBG_ERR, "malloc failed");
2964 newrealm->accsrvconfs = list_create();
2965 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2966 debug(DBG_ERR, "malloc failed");
2970 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2972 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2973 debug(DBG_ERR, "pthread_create failed");
2981 list_removedata(realm->subrealms, newrealm);
2982 freerealm(newrealm);
2984 freeserver(srvconf->servers, 1);
2986 debug(DBG_ERR, "failed to create dynamic server");
2989 pthread_mutex_unlock(&realm->subrealms_mutex);
2992 int dynamicconfig(struct server *server) {
2993 int ok, fd[2], status;
2995 struct clsrvconf *conf = server->conf;
2996 struct gconffile *cf = NULL;
2998 /* for now we only learn hostname/address */
2999 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
3002 debug(DBG_ERR, "dynamicconfig: pipe error");
3007 debug(DBG_ERR, "dynamicconfig: fork error");
3011 } else if (pid == 0) {
3014 if (fd[1] != STDOUT_FILENO) {
3015 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
3016 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
3019 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
3020 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
3024 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
3025 ok = getgenericconfig(&cf, NULL,
3026 "Server", CONF_CBK, confserver_cb, (void *)conf,
3031 if (waitpid(pid, &status, 0) < 0) {
3032 debug(DBG_ERR, "dynamicconfig: wait error");
3037 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
3045 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
3049 int addmatchcertattr(struct clsrvconf *conf) {
3053 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
3054 r = &conf->certcnregex;
3055 v = conf->matchcertattr + 4;
3056 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
3057 r = &conf->certuriregex;
3058 v = conf->matchcertattr + 20;
3063 /* regexp, remove optional trailing / if present */
3064 if (v[strlen(v) - 1] == '/')
3065 v[strlen(v) - 1] = '\0';
3069 *r = malloc(sizeof(regex_t));
3071 debug(DBG_ERR, "malloc failed");
3074 if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
3077 debug(DBG_ERR, "failed to compile regular expression %s", v);
3083 int addrewriteattr(struct clsrvconf *conf) {
3086 v = conf->rewriteattr + 11;
3087 if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
3089 /* regexp, remove optional trailing / if present */
3090 if (v[strlen(v) - 1] == '/')
3091 v[strlen(v) - 1] = '\0';
3099 conf->rewriteattrregex = malloc(sizeof(regex_t));
3100 if (!conf->rewriteattrregex) {
3101 debug(DBG_ERR, "malloc failed");
3105 conf->rewriteattrreplacement = stringcopy(w, 0);
3106 if (!conf->rewriteattrreplacement) {
3107 free(conf->rewriteattrregex);
3108 conf->rewriteattrregex = NULL;
3112 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
3113 free(conf->rewriteattrregex);
3114 conf->rewriteattrregex = NULL;
3115 free(conf->rewriteattrreplacement);
3116 conf->rewriteattrreplacement = NULL;
3117 debug(DBG_ERR, "failed to compile regular expression %s", v);
3124 /* should accept both names and numeric values, only numeric right now */
3125 uint8_t attrname2val(char *attrname) {
3128 val = atoi(attrname);
3129 return val > 0 && val < 256 ? val : 0;
3132 /* should accept both names and numeric values, only numeric right now */
3133 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
3136 *vendor = atoi(attrname);
3137 s = strchr(attrname, ':');
3142 *type = atoi(s + 1);
3143 return *type >= 0 && *type < 256;
3146 struct rewrite *getrewrite(char *alt1, char *alt2) {
3147 struct list_node *entry;
3148 struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
3150 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
3151 r = (struct rewriteconf *)entry->data;
3152 if (!strcasecmp(r->name, alt1)) {
3156 if (!r2 && alt2 && !strcasecmp(r->name, alt2))
3166 void addrewrite(char *value, char **attrs, char **vattrs) {
3167 struct rewriteconf *new;
3168 struct rewrite *rewrite = NULL;
3171 uint32_t *p, *va = NULL;
3175 for (; attrs[n]; n++);
3176 a = malloc((n + 1) * sizeof(uint8_t));
3178 debugx(1, DBG_ERR, "malloc failed");
3180 for (i = 0; i < n; i++) {
3181 if (!(a[i] = attrname2val(attrs[i])))
3182 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
3191 for (; vattrs[n]; n++);
3192 va = malloc((2 * n + 1) * sizeof(uint32_t));
3194 debugx(1, DBG_ERR, "malloc failed");
3196 for (p = va, i = 0; i < n; i++, p += 2) {
3197 if (!vattrname2val(vattrs[i], p, p + 1))
3198 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
3206 rewrite = malloc(sizeof(struct rewrite));
3208 debugx(1, DBG_ERR, "malloc failed");
3209 rewrite->removeattrs = a;
3210 rewrite->removevendorattrs = va;
3213 new = malloc(sizeof(struct rewriteconf));
3214 if (!new || !list_push(rewriteconfs, new))
3215 debugx(1, DBG_ERR, "malloc failed");
3217 memset(new, 0, sizeof(struct rewriteconf));
3218 new->name = stringcopy(value, 0);
3220 debugx(1, DBG_ERR, "malloc failed");
3222 new->rewrite = rewrite;
3223 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3226 void freeclsrvconf(struct clsrvconf *conf) {
3228 free(conf->conftype);
3233 free(conf->matchcertattr);
3234 if (conf->certcnregex)
3235 regfree(conf->certcnregex);
3236 if (conf->certuriregex)
3237 regfree(conf->certuriregex);
3238 free(conf->confrewrite);
3239 free(conf->rewriteattr);
3240 if (conf->rewriteattrregex)
3241 regfree(conf->rewriteattrregex);
3242 free(conf->rewriteattrreplacement);
3243 free(conf->dynamiclookupcommand);
3245 SSL_CTX_free(conf->ssl_ctx);
3246 free(conf->rewrite);
3248 freeaddrinfo(conf->addrinfo);
3249 list_destroy(conf->clients);
3250 free(conf->servers);
3254 int mergeconfstring(char **dst, char **src) {
3263 t = stringcopy(*dst, 0);
3265 debug(DBG_ERR, "malloc failed");
3273 /* assumes dst is a shallow copy */
3274 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3275 if (!mergeconfstring(&dst->name, &src->name) ||
3276 !mergeconfstring(&dst->conftype, &src->conftype) ||
3277 !mergeconfstring(&dst->host, &src->host) ||
3278 !mergeconfstring(&dst->port, &src->port) ||
3279 !mergeconfstring(&dst->secret, &src->secret) ||
3280 !mergeconfstring(&dst->tls, &src->tls) ||
3281 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3282 !mergeconfstring(&dst->confrewrite, &src->confrewrite))
3284 dst->statusserver = src->statusserver;
3285 dst->certnamecheck = src->certnamecheck;
3289 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3290 struct clsrvconf *conf;
3292 debug(DBG_DBG, "confclient_cb called for %s", block);
3294 conf = malloc(sizeof(struct clsrvconf));
3295 if (!conf || !list_push(clconfs, conf))
3296 debugx(1, DBG_ERR, "malloc failed");
3297 memset(conf, 0, sizeof(struct clsrvconf));
3298 conf->certnamecheck = 1;
3300 if (!getgenericconfig(cf, block,
3301 "type", CONF_STR, &conf->conftype,
3302 "host", CONF_STR, &conf->host,
3303 "secret", CONF_STR, &conf->secret,
3304 "tls", CONF_STR, &conf->tls,
3305 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3306 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3307 "rewrite", CONF_STR, &conf->confrewrite,
3308 "rewriteattribute", CONF_STR, &conf->rewriteattr,
3311 debugx(1, DBG_ERR, "configuration error");
3313 conf->name = stringcopy(val, 0);
3315 conf->host = stringcopy(val, 0);
3317 if (conf->conftype && !strcasecmp(conf->conftype, "udp")) {
3320 } else if (conf->conftype && !strcasecmp(conf->conftype, "tls")) {
3321 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultclient", "default");
3323 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3324 if (conf->matchcertattr && !addmatchcertattr(conf))
3325 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3329 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
3331 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
3333 if (conf->rewriteattr) {
3334 if (!addrewriteattr(conf))
3335 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3338 if (!resolvepeer(conf, 0))
3339 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3341 if (!conf->secret) {
3342 if (conf->type == 'U')
3343 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
3344 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
3349 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3350 switch (conf->type) {
3353 conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
3356 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultserver", "default");
3357 if (!conf->ssl_ctx) {
3358 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3361 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3362 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3366 conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
3370 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
3372 if (!conf->secret) {
3373 if (conf->type == 'U')
3374 debug(DBG_ERR, "error in block %s, secret must be specified for UDP", block);
3375 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
3376 if (!conf->secret) {
3377 debug(DBG_ERR, "malloc failed");
3382 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3383 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3389 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3390 struct clsrvconf *conf, *resconf;
3392 debug(DBG_DBG, "confserver_cb called for %s", block);
3394 conf = malloc(sizeof(struct clsrvconf));
3396 debug(DBG_ERR, "malloc failed");
3399 memset(conf, 0, sizeof(struct clsrvconf));
3400 resconf = (struct clsrvconf *)arg;
3402 conf->statusserver = resconf->statusserver;
3403 conf->certnamecheck = resconf->certnamecheck;
3405 conf->certnamecheck = 1;
3407 if (!getgenericconfig(cf, block,
3408 "type", CONF_STR, &conf->conftype,
3409 "host", CONF_STR, &conf->host,
3410 "port", CONF_STR, &conf->port,
3411 "secret", CONF_STR, &conf->secret,
3412 "tls", CONF_STR, &conf->tls,
3413 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3414 "rewrite", CONF_STR, &conf->confrewrite,
3415 "StatusServer", CONF_BLN, &conf->statusserver,
3416 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3417 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3420 debug(DBG_ERR, "configuration error");
3424 conf->name = stringcopy(val, 0);
3426 debug(DBG_ERR, "malloc failed");
3430 conf->host = stringcopy(val, 0);
3432 debug(DBG_ERR, "malloc failed");
3438 if (!mergesrvconf(resconf, conf))
3444 if (conf->conftype && !strcasecmp(conf->conftype, "udp"))
3446 else if (conf->conftype && !strcasecmp(conf->conftype, "tls"))
3449 debug(DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
3453 if (resconf || !conf->dynamiclookupcommand) {
3454 if (!compileserverconfig(conf, block))
3461 switch (conf->type) {
3472 if (!list_push(srvconfs, conf)) {
3473 debug(DBG_ERR, "malloc failed");
3479 freeclsrvconf(conf);
3483 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3484 char **servers = NULL, **accservers = NULL, *msg = NULL;
3486 debug(DBG_DBG, "confrealm_cb called for %s", block);
3488 if (!getgenericconfig(cf, block,
3489 "server", CONF_MSTR, &servers,
3490 "accountingServer", CONF_MSTR, &accservers,
3491 "ReplyMessage", CONF_STR, &msg,
3494 debugx(1, DBG_ERR, "configuration error");
3496 addrealm(realms, val, servers, accservers, msg);
3500 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3501 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
3503 debug(DBG_DBG, "conftls_cb called for %s", block);
3505 if (!getgenericconfig(cf, block,
3506 "CACertificateFile", CONF_STR, &cacertfile,
3507 "CACertificatePath", CONF_STR, &cacertpath,
3508 "CertificateFile", CONF_STR, &certfile,
3509 "CertificateKeyFile", CONF_STR, &certkeyfile,
3510 "CertificateKeyPassword", CONF_STR, &certkeypwd,
3513 debugx(1, DBG_ERR, "configuration error");
3515 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
3524 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3525 char **attrs = NULL, **vattrs = NULL;
3527 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3529 if (!getgenericconfig(cf, block,
3530 "removeAttribute", CONF_MSTR, &attrs,
3531 "removeVendorAttribute", CONF_MSTR, &vattrs,
3534 debugx(1, DBG_ERR, "configuration error");
3535 addrewrite(val, attrs, vattrs);
3539 void getmainconfig(const char *configfile) {
3540 char *loglevel = NULL;
3541 struct gconffile *cfs;
3543 cfs = openconfigfile(configfile);
3544 memset(&options, 0, sizeof(options));
3546 clconfs = list_create();
3548 debugx(1, DBG_ERR, "malloc failed");
3550 srvconfs = list_create();
3552 debugx(1, DBG_ERR, "malloc failed");
3554 realms = list_create();
3556 debugx(1, DBG_ERR, "malloc failed");
3558 tlsconfs = list_create();
3560 debugx(1, DBG_ERR, "malloc failed");
3562 rewriteconfs = list_create();
3564 debugx(1, DBG_ERR, "malloc failed");
3566 if (!getgenericconfig(&cfs, NULL,
3567 "ListenUDP", CONF_STR, &options.listenudp,
3568 "ListenTCP", CONF_STR, &options.listentcp,
3569 "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
3570 "SourceUDP", CONF_STR, &options.sourceudp,
3571 "SourceTCP", CONF_STR, &options.sourcetcp,
3572 "LogLevel", CONF_STR, &loglevel,
3573 "LogDestination", CONF_STR, &options.logdestination,
3574 "LoopPrevention", CONF_BLN, &options.loopprevention,
3575 "Client", CONF_CBK, confclient_cb, NULL,
3576 "Server", CONF_CBK, confserver_cb, NULL,
3577 "Realm", CONF_CBK, confrealm_cb, NULL,
3578 "TLS", CONF_CBK, conftls_cb, NULL,
3579 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3582 debugx(1, DBG_ERR, "configuration error");
3585 if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
3586 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
3587 options.loglevel = *loglevel - '0';
3592 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3595 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3598 *configfile = optarg;
3601 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3602 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3603 *loglevel = *optarg - '0';
3612 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3617 if (!(argc - optind))
3621 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3625 int daemon(int a, int b) {
3633 for (i = 0; i < 3; i++) {
3635 open("/dev/null", O_RDWR);
3641 void *sighandler(void *arg) {
3646 sigemptyset(&sigset);
3647 sigaddset(&sigset, SIGPIPE);
3648 sigwait(&sigset, &sig);
3649 /* only get SIGPIPE right now, so could simplify below code */
3652 /* completely ignoring this */
3655 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3658 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3663 int main(int argc, char **argv) {
3664 pthread_t sigth, udpserverth, udpaccserverth, udpclient4rdth, udpclient6rdth;
3666 struct list_node *entry;
3667 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3668 char *configfile = NULL;
3669 struct clsrvconf *srvconf;
3671 debug_init("radsecproxy");
3672 debug_set_level(DEBUG_LEVEL);
3673 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3675 debug_set_level(loglevel);
3676 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3678 options.loglevel = loglevel;
3679 else if (options.loglevel)
3680 debug_set_level(options.loglevel);
3682 free(options.logdestination);
3683 options.logdestination = NULL;
3685 if (!options.logdestination)
3686 options.logdestination = "x-syslog:///";
3687 debug_set_destination(options.logdestination);
3688 free(options.logdestination);
3691 if (!list_first(clconfs))
3692 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3693 if (!list_first(srvconfs))
3694 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
3695 if (!list_first(realms))
3696 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3699 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3701 if (!foreground && (daemon(0, 0) < 0))
3702 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3704 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3706 sigemptyset(&sigset);
3707 /* exit on all but SIGPIPE, ignore more? */
3708 sigaddset(&sigset, SIGPIPE);
3709 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3710 pthread_create(&sigth, NULL, sighandler, NULL);
3712 if (client_udp_count) {
3713 udp_server_replyq = newreplyq();
3714 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
3715 debugx(1, DBG_ERR, "pthread_create failed");
3716 if (options.listenaccudp)
3717 if (pthread_create(&udpaccserverth, NULL, udpaccserverrd, NULL))
3718 debugx(1, DBG_ERR, "pthread_create failed");
3721 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3722 srvconf = (struct clsrvconf *)entry->data;
3723 if (srvconf->dynamiclookupcommand)
3725 if (!addserver(srvconf))
3726 debugx(1, DBG_ERR, "failed to add server");
3727 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3728 (void *)(srvconf->servers)))
3729 debugx(1, DBG_ERR, "pthread_create failed");
3731 /* srcudpres no longer needed, while srctcpres is needed later */
3733 freeaddrinfo(srcudpres);
3736 if (udp_client4_sock >= 0)
3737 if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
3738 debugx(1, DBG_ERR, "pthread_create failed");
3739 if (udp_client6_sock >= 0)
3740 if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
3741 debugx(1, DBG_ERR, "pthread_create failed");
3743 if (client_tls_count)
3744 return tlslistener();
3746 /* just hang around doing nothing, anything to do here? */