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>
43 #include <sys/types.h>
44 #include <arpa/inet.h>
48 #include <openssl/ssl.h>
49 #include <openssl/rand.h>
50 #include <openssl/err.h>
51 #include <openssl/md5.h>
52 #include <openssl/hmac.h>
53 #include <openssl/x509v3.h>
58 #include "radsecproxy.h"
60 static struct options options;
61 struct list *clconfs, *srvconfs, *realms, *tlsconfs, *rewriteconfs;
63 static int client_udp_count = 0;
64 static int client_tls_count = 0;
66 static struct addrinfo *srcudpres = NULL;
67 static struct addrinfo *srctcpres = NULL;
69 static struct replyq *udp_server_replyq = NULL;
70 static int udp_server_sock = -1;
71 static int udp_accserver_sock = -1;
72 static int udp_client4_sock = -1;
73 static int udp_client6_sock = -1;
74 static pthread_mutex_t *ssl_locks = NULL;
75 static long *ssl_lock_count;
79 /* callbacks for making OpenSSL thread safe */
80 unsigned long ssl_thread_id() {
81 return (unsigned long)pthread_self();
84 void ssl_locking_callback(int mode, int type, const char *file, int line) {
85 if (mode & CRYPTO_LOCK) {
86 pthread_mutex_lock(&ssl_locks[type]);
87 ssl_lock_count[type]++;
89 pthread_mutex_unlock(&ssl_locks[type]);
92 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
93 int pwdlen = strlen(userdata);
94 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
96 memcpy(buf, userdata, pwdlen);
100 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
105 err_cert = X509_STORE_CTX_get_current_cert(ctx);
106 err = X509_STORE_CTX_get_error(ctx);
107 depth = X509_STORE_CTX_get_error_depth(ctx);
109 if (depth > MAX_CERT_DEPTH) {
111 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
112 X509_STORE_CTX_set_error(ctx, err);
116 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
117 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
120 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
121 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
122 debug(DBG_WARN, "\tIssuer=%s", buf);
124 case X509_V_ERR_CERT_NOT_YET_VALID:
125 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
126 debug(DBG_WARN, "\tCertificate not yet valid");
128 case X509_V_ERR_CERT_HAS_EXPIRED:
129 debug(DBG_WARN, "Certificate has expired");
131 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
132 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
137 printf("certificate verify returns %d\n", ok);
142 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
143 struct addrinfo hints, *addrinfo, *res;
147 slash = conf->host ? strchr(conf->host, '/') : NULL;
151 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
155 if (*s < '0' || *s > '9') {
156 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
159 plen = atoi(slash + 1);
160 if (plen < 0 || plen > 128) {
161 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
166 memset(&hints, 0, sizeof(hints));
167 hints.ai_socktype = (conf->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
168 hints.ai_family = AF_UNSPEC;
169 hints.ai_flags = ai_flags;
170 if (!conf->host && !conf->port) {
171 /* getaddrinfo() doesn't like host and port to be NULL */
172 if (getaddrinfo(conf->host, DEFAULT_UDP_PORT, &hints, &addrinfo)) {
173 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
176 for (res = addrinfo; res; res = res->ai_next) {
177 switch (res->ai_family) {
179 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
182 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
188 hints.ai_flags |= AI_NUMERICHOST;
189 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
190 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
195 switch (addrinfo->ai_family) {
198 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
199 freeaddrinfo(addrinfo);
206 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
207 freeaddrinfo(addrinfo);
210 conf->prefixlen = plen;
212 conf->prefixlen = 255;
215 freeaddrinfo(conf->addrinfo);
216 conf->addrinfo = addrinfo;
220 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
222 struct addrinfo *res;
224 for (res = addrinfo; res; res = res->ai_next) {
225 if (family != AF_UNSPEC && family != res->ai_family)
227 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
229 debug(DBG_WARN, "bindtoaddr: socket failed");
233 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
236 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
239 if (!bind(s, res->ai_addr, res->ai_addrlen))
241 debug(DBG_WARN, "bindtoaddr: bind failed");
247 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
252 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
256 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
258 debugx(1, DBG_ERR, "no ] matching initial [");
262 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
265 debugx(1, DBG_ERR, "missing host/address");
267 conf->host = stringcopy(field, p - field);
270 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
271 debugx(1, DBG_ERR, "unexpected character after ]");
274 /* port number or service name is specified */;
276 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
278 debugx(1, DBG_ERR, "syntax error, : but no following port");
279 conf->port = stringcopy(field, p - field);
281 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
285 struct clsrvconf *resolve_hostport(char type, char *lconf, char *default_port) {
286 struct clsrvconf *conf;
288 conf = malloc(sizeof(struct clsrvconf));
290 debugx(1, DBG_ERR, "malloc failed");
291 memset(conf, 0, sizeof(struct clsrvconf));
294 parsehostport(lconf, conf, default_port);
295 if (!strcmp(conf->host, "*")) {
300 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
301 if (!resolvepeer(conf, AI_PASSIVE))
302 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
306 void freeclsrvres(struct clsrvconf *res) {
310 freeaddrinfo(res->addrinfo);
314 int connecttcp(struct addrinfo *addrinfo) {
316 struct addrinfo *res;
319 for (res = addrinfo; res; res = res->ai_next) {
320 s = bindtoaddr(srctcpres, res->ai_family, 1, 1);
322 debug(DBG_WARN, "connecttoserver: socket failed");
325 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
327 debug(DBG_WARN, "connecttoserver: connect failed");
334 /* returns 1 if the len first bits are equal, else 0 */
335 int prefixmatch(void *a1, void *a2, uint8_t len) {
336 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
338 if (l && memcmp(a1, a2, l))
343 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
346 /* returns next config with matching address, or NULL */
347 struct clsrvconf *find_conf(char type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
348 struct sockaddr_in6 *sa6 = NULL;
349 struct in_addr *a4 = NULL;
350 struct addrinfo *res;
351 struct list_node *entry;
352 struct clsrvconf *conf;
354 if (addr->sa_family == AF_INET6) {
355 sa6 = (struct sockaddr_in6 *)addr;
356 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
357 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
361 a4 = &((struct sockaddr_in *)addr)->sin_addr;
363 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
364 conf = (struct clsrvconf *)entry->data;
365 if (conf->type == type) {
366 if (conf->prefixlen == 255) {
367 for (res = conf->addrinfo; res; res = res->ai_next)
368 if ((a4 && res->ai_family == AF_INET &&
369 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
370 (sa6 && res->ai_family == AF_INET6 &&
371 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
377 res = conf->addrinfo;
379 ((a4 && res->ai_family == AF_INET &&
380 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
381 (sa6 && res->ai_family == AF_INET6 &&
382 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
393 struct replyq *newreplyq() {
394 struct replyq *replyq;
396 replyq = malloc(sizeof(struct replyq));
398 debugx(1, DBG_ERR, "malloc failed");
399 replyq->replies = list_create();
400 if (!replyq->replies)
401 debugx(1, DBG_ERR, "malloc failed");
402 pthread_mutex_init(&replyq->mutex, NULL);
403 pthread_cond_init(&replyq->cond, NULL);
407 struct client *addclient(struct clsrvconf *conf) {
408 struct client *new = malloc(sizeof(struct client));
411 debug(DBG_ERR, "malloc failed");
414 if (!conf->clients) {
415 conf->clients = list_create();
416 if (!conf->clients) {
417 debug(DBG_ERR, "malloc failed");
422 memset(new, 0, sizeof(struct client));
424 new->replyq = conf->type == 'T' ? newreplyq() : udp_server_replyq;
426 list_push(conf->clients, new);
430 void removeclient(struct client *client) {
431 struct list_node *entry;
433 if (!client || !client->conf->clients)
436 pthread_mutex_lock(&client->replyq->mutex);
437 for (entry = list_first(client->replyq->replies); entry; entry = list_next(entry))
438 free(((struct reply *)entry)->buf);
439 list_destroy(client->replyq->replies);
440 pthread_cond_destroy(&client->replyq->cond);
441 pthread_mutex_unlock(&client->replyq->mutex);
442 pthread_mutex_destroy(&client->replyq->mutex);
443 list_removedata(client->conf->clients, client);
447 void removeclientrqs(struct client *client) {
448 struct list_node *entry;
449 struct server *server;
453 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
454 server = ((struct clsrvconf *)entry->data)->servers;
455 pthread_mutex_lock(&server->newrq_mutex);
456 for (i = 0; i < MAX_REQUESTS; i++) {
457 rq = server->requests + i;
458 if (rq->from == client)
461 pthread_mutex_unlock(&server->newrq_mutex);
465 void addserver(struct clsrvconf *conf) {
466 struct clsrvconf *res;
469 debugx(1, DBG_ERR, "addserver: currently works with just one server per conf");
471 conf->servers = malloc(sizeof(struct server));
473 debugx(1, DBG_ERR, "malloc failed");
474 memset(conf->servers, 0, sizeof(struct server));
475 conf->servers->conf = conf;
477 if (conf->type == 'U') {
479 res = resolve_hostport('U', options.sourceudp, NULL);
480 srcudpres = res->addrinfo;
481 res->addrinfo = NULL;
484 switch (conf->addrinfo->ai_family) {
486 if (udp_client4_sock < 0) {
487 udp_client4_sock = bindtoaddr(srcudpres, AF_INET, 0, 1);
488 if (udp_client4_sock < 0)
489 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
491 conf->servers->sock = udp_client4_sock;
494 if (udp_client6_sock < 0) {
495 udp_client6_sock = bindtoaddr(srcudpres, AF_INET6, 0, 1);
496 if (udp_client6_sock < 0)
497 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
499 conf->servers->sock = udp_client6_sock;
502 debugx(1, DBG_ERR, "addserver: unsupported address family");
507 res = resolve_hostport('T', options.sourcetcp, NULL);
508 srctcpres = res->addrinfo;
509 res->addrinfo = NULL;
512 conf->servers->sock = -1;
515 pthread_mutex_init(&conf->servers->lock, NULL);
516 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
517 if (!conf->servers->requests)
518 debugx(1, DBG_ERR, "malloc failed");
519 conf->servers->newrq = 0;
520 pthread_mutex_init(&conf->servers->newrq_mutex, NULL);
521 pthread_cond_init(&conf->servers->newrq_cond, NULL);
524 /* exactly one of client and server must be non-NULL */
525 /* return who we received from in *client or *server */
526 /* return from in sa if not NULL */
527 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
529 unsigned char buf[4], *rad;
530 struct sockaddr_storage from;
531 socklen_t fromlen = sizeof(from);
533 struct list_node *node;
539 if (select(s + 1, &readfds, NULL, NULL, NULL) < 1)
541 cnt = recvfrom(s, buf, 4, MSG_PEEK, (struct sockaddr *)&from, &fromlen);
543 debug(DBG_WARN, "radudpget: recv failed");
547 p = find_conf('U', (struct sockaddr *)&from, client ? clconfs : srvconfs, NULL);
549 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
556 debug(DBG_WARN, "radudpget: length too small");
563 debug(DBG_ERR, "radudpget: malloc failed");
568 cnt = recv(s, rad, len, MSG_TRUNC);
569 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
572 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
578 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
581 node = list_first(p->clients);
582 *client = node ? (struct client *)node->data : addclient(p);
588 *server = p->servers;
596 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
597 int loc, i, l, n, r = 0;
600 STACK_OF(GENERAL_NAME) *alt;
603 debug(DBG_DBG, "subjectaltnameaddr");
605 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
609 ex = X509_get_ext(cert, loc);
610 alt = X509V3_EXT_d2i(ex);
614 n = sk_GENERAL_NAME_num(alt);
615 for (i = 0; i < n; i++) {
616 gn = sk_GENERAL_NAME_value(alt, i);
617 if (gn->type != GEN_IPADD)
620 v = (char *)ASN1_STRING_data(gn->d.ia5);
621 l = ASN1_STRING_length(gn->d.ia5);
622 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
623 && !memcmp(v, &addr, l)) {
628 GENERAL_NAMES_free(alt);
632 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
639 nm = X509_get_subject_name(cert);
642 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
645 e = X509_NAME_get_entry(nm, loc);
646 t = X509_NAME_ENTRY_get_data(e);
647 v = (char *) ASN1_STRING_data(t);
648 l = ASN1_STRING_length(t);
652 if (l == strlen(exact) && !strncasecmp(exact, v, l))
655 s = stringcopy((char *)v, l);
657 debug(DBG_ERR, "malloc failed");
660 if (regexec(regex, s, 0, NULL, 0)) {
671 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
672 int loc, i, l, n, r = 0;
675 STACK_OF(GENERAL_NAME) *alt;
678 debug(DBG_DBG, "subjectaltnameregexp");
680 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
684 ex = X509_get_ext(cert, loc);
685 alt = X509V3_EXT_d2i(ex);
689 n = sk_GENERAL_NAME_num(alt);
690 for (i = 0; i < n; i++) {
691 gn = sk_GENERAL_NAME_value(alt, i);
692 if (gn->type != type)
695 v = (char *)ASN1_STRING_data(gn->d.ia5);
696 l = ASN1_STRING_length(gn->d.ia5);
700 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
703 if (memcmp(v, exact, l))
706 s = stringcopy((char *)v, l);
708 debug(DBG_ERR, "malloc failed");
711 if (regexec(regex, s, 0, NULL, 0)) {
720 GENERAL_NAMES_free(alt);
724 X509 *verifytlscert(SSL *ssl) {
728 if (SSL_get_verify_result(ssl) != X509_V_OK) {
729 debug(DBG_ERR, "verifytlscert: basic validation failed");
730 while ((error = ERR_get_error()))
731 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
735 cert = SSL_get_peer_certificate(ssl);
737 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
741 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
743 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
744 struct in6_addr addr;
746 if (conf->certnamecheck && conf->prefixlen == 255) {
747 if (inet_pton(AF_INET, conf->host, &addr))
749 else if (inet_pton(AF_INET6, conf->host, &addr))
752 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
755 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
758 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
760 if (!cnregexp(cert, conf->host, NULL)) {
761 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
764 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
767 if (conf->certcnregex) {
768 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
769 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
772 debug(DBG_DBG, "verifyconfcert: CN matching regex");
774 if (conf->certuriregex) {
775 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
776 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
779 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
784 void tlsconnect(struct server *server, struct timeval *when, char *text) {
789 debug(DBG_DBG, "tlsconnect called from %s", text);
790 pthread_mutex_lock(&server->lock);
791 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
792 /* already reconnected, nothing to do */
793 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
794 pthread_mutex_unlock(&server->lock);
798 debug(DBG_DBG, "tlsconnect %s", text);
801 gettimeofday(&now, NULL);
802 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
803 if (server->connectionok) {
804 server->connectionok = 0;
806 } else if (elapsed < 1)
808 else if (elapsed < 60) {
809 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
811 } else if (elapsed < 100000) {
812 debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
815 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
816 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
817 if (server->sock >= 0)
819 if ((server->sock = connecttcp(server->conf->addrinfo)) < 0) {
820 debug(DBG_ERR, "tlsconnect: connecttcp failed");
824 SSL_free(server->ssl);
825 server->ssl = SSL_new(server->conf->ssl_ctx);
826 SSL_set_fd(server->ssl, server->sock);
827 if (SSL_connect(server->ssl) <= 0)
829 cert = verifytlscert(server->ssl);
832 if (verifyconfcert(cert, server->conf)) {
838 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
839 gettimeofday(&server->lastconnecttry, NULL);
840 pthread_mutex_unlock(&server->lock);
843 unsigned char *radtlsget(SSL *ssl) {
845 unsigned char buf[4], *rad;
848 for (total = 0; total < 4; total += cnt) {
849 cnt = SSL_read(ssl, buf + total, 4 - total);
851 debug(DBG_ERR, "radtlsget: connection lost");
852 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
853 /* remote end sent close_notify, send one back */
863 debug(DBG_ERR, "radtlsget: malloc failed");
868 for (; total < len; total += cnt) {
869 cnt = SSL_read(ssl, rad + total, len - total);
871 debug(DBG_ERR, "radtlsget: connection lost");
872 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
873 /* remote end sent close_notify, send one back */
885 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
888 debug(DBG_DBG, "radtlsget: got %d bytes", total);
892 int clientradputudp(struct server *server, unsigned char *rad) {
894 struct sockaddr_storage sa;
895 struct sockaddr *sap;
896 struct clsrvconf *conf = server->conf;
897 in_port_t *port = NULL;
901 if (*rad == RAD_Accounting_Request) {
902 sap = (struct sockaddr *)&sa;
903 memcpy(sap, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen);
905 sap = conf->addrinfo->ai_addr;
907 switch (sap->sa_family) {
909 port = &((struct sockaddr_in *)sap)->sin_port;
912 port = &((struct sockaddr_in6 *)sap)->sin6_port;
918 if (*rad == RAD_Accounting_Request)
919 *port = htons(ntohs(*port) + 1);
921 if (sendto(server->sock, rad, len, 0, sap, conf->addrinfo->ai_addrlen) >= 0) {
922 debug(DBG_DBG, "clienradputudp: sent UDP of length %d to %s port %d", len, conf->host, ntohs(*port));
926 debug(DBG_WARN, "clientradputudp: send failed");
930 int clientradputtls(struct server *server, unsigned char *rad) {
934 struct timeval lastconnecttry;
935 struct clsrvconf *conf = server->conf;
938 lastconnecttry = server->lastconnecttry;
939 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
940 while ((error = ERR_get_error()))
941 debug(DBG_ERR, "clientradputtls: TLS: %s", ERR_error_string(error, NULL));
942 tlsconnect(server, &lastconnecttry, "clientradputtls");
943 lastconnecttry = server->lastconnecttry;
946 server->connectionok = 1;
947 debug(DBG_DBG, "clientradputtls: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
951 int clientradput(struct server *server, unsigned char *rad) {
952 switch (server->conf->type) {
954 return clientradputudp(server, rad);
956 return clientradputtls(server, rad);
961 int radsign(unsigned char *rad, unsigned char *sec) {
962 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
963 static unsigned char first = 1;
964 static EVP_MD_CTX mdctx;
968 pthread_mutex_lock(&lock);
970 EVP_MD_CTX_init(&mdctx);
974 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
975 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
976 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
977 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
979 pthread_mutex_unlock(&lock);
983 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
984 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
985 static unsigned char first = 1;
986 static EVP_MD_CTX mdctx;
987 unsigned char hash[EVP_MAX_MD_SIZE];
991 pthread_mutex_lock(&lock);
993 EVP_MD_CTX_init(&mdctx);
999 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1000 EVP_DigestUpdate(&mdctx, rad, 4) &&
1001 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
1002 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
1003 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1004 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
1006 !memcmp(hash, rad + 4, 16));
1007 pthread_mutex_unlock(&lock);
1011 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
1012 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1013 static unsigned char first = 1;
1014 static HMAC_CTX hmacctx;
1015 unsigned int md_len;
1016 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
1018 pthread_mutex_lock(&lock);
1020 HMAC_CTX_init(&hmacctx);
1024 memcpy(auth, authattr, 16);
1025 memset(authattr, 0, 16);
1027 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1028 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1029 HMAC_Final(&hmacctx, hash, &md_len);
1030 memcpy(authattr, auth, 16);
1032 debug(DBG_WARN, "message auth computation failed");
1033 pthread_mutex_unlock(&lock);
1037 if (memcmp(auth, hash, 16)) {
1038 debug(DBG_WARN, "message authenticator, wrong value");
1039 pthread_mutex_unlock(&lock);
1043 pthread_mutex_unlock(&lock);
1047 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
1048 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1049 static unsigned char first = 1;
1050 static HMAC_CTX hmacctx;
1051 unsigned int md_len;
1056 pthread_mutex_lock(&lock);
1058 HMAC_CTX_init(&hmacctx);
1062 memset(authattrval, 0, 16);
1064 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1065 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1066 HMAC_Final(&hmacctx, authattrval, &md_len);
1068 debug(DBG_WARN, "message auth computation failed");
1069 pthread_mutex_unlock(&lock);
1073 pthread_mutex_unlock(&lock);
1077 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
1078 while (length > 1) {
1079 if (ATTRTYPE(attrs) == type)
1081 length -= ATTRLEN(attrs);
1082 attrs += ATTRLEN(attrs);
1087 void freerqdata(struct request *rq) {
1088 if (rq->origusername)
1089 free(rq->origusername);
1094 void sendrq(struct server *to, struct request *rq) {
1098 pthread_mutex_lock(&to->newrq_mutex);
1099 /* might simplify if only try nextid, might be ok */
1100 for (i = to->nextid; i < MAX_REQUESTS; i++)
1101 if (!to->requests[i].buf)
1103 if (i == MAX_REQUESTS) {
1104 for (i = 0; i < to->nextid; i++)
1105 if (!to->requests[i].buf)
1107 if (i == to->nextid) {
1108 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
1114 rq->buf[1] = (char)i;
1116 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1117 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1122 if (*(uint8_t *)rq->buf == RAD_Accounting_Request) {
1123 if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
1124 debug(DBG_WARN, "sendrq: failed to sign Accounting-Request message");
1130 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1131 to->requests[i] = *rq;
1136 debug(DBG_DBG, "sendrq: signalling client writer");
1137 pthread_cond_signal(&to->newrq_cond);
1140 pthread_mutex_unlock(&to->newrq_mutex);
1143 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
1144 struct reply *reply;
1147 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1149 debug(DBG_WARN, "sendreply: failed to sign message");
1153 reply = malloc(sizeof(struct reply));
1156 debug(DBG_ERR, "sendreply: malloc failed");
1159 memset(reply, 0, sizeof(struct reply));
1162 reply->tosa = *tosa;
1164 pthread_mutex_lock(&to->replyq->mutex);
1166 first = list_first(to->replyq->replies) == NULL;
1168 if (!list_push(to->replyq->replies, reply)) {
1169 pthread_mutex_unlock(&to->replyq->mutex);
1172 debug(DBG_ERR, "sendreply: malloc failed");
1177 debug(DBG_DBG, "signalling server writer");
1178 pthread_cond_signal(&to->replyq->cond);
1180 pthread_mutex_unlock(&to->replyq->mutex);
1183 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1184 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1185 static unsigned char first = 1;
1186 static EVP_MD_CTX mdctx;
1187 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1188 unsigned int md_len;
1189 uint8_t i, offset = 0, out[128];
1191 pthread_mutex_lock(&lock);
1193 EVP_MD_CTX_init(&mdctx);
1199 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1200 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1201 !EVP_DigestUpdate(&mdctx, input, 16) ||
1202 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1204 pthread_mutex_unlock(&lock);
1207 for (i = 0; i < 16; i++)
1208 out[offset + i] = hash[i] ^ in[offset + i];
1209 input = out + offset - 16;
1214 memcpy(in, out, len);
1215 pthread_mutex_unlock(&lock);
1219 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1220 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1221 static unsigned char first = 1;
1222 static EVP_MD_CTX mdctx;
1223 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1224 unsigned int md_len;
1225 uint8_t i, offset = 0, out[128];
1227 pthread_mutex_lock(&lock);
1229 EVP_MD_CTX_init(&mdctx);
1235 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1236 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1237 !EVP_DigestUpdate(&mdctx, input, 16) ||
1238 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1240 pthread_mutex_unlock(&lock);
1243 for (i = 0; i < 16; i++)
1244 out[offset + i] = hash[i] ^ in[offset + i];
1245 input = in + offset;
1250 memcpy(in, out, len);
1251 pthread_mutex_unlock(&lock);
1255 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1256 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1257 static unsigned char first = 1;
1258 static EVP_MD_CTX mdctx;
1259 unsigned char hash[EVP_MAX_MD_SIZE];
1260 unsigned int md_len;
1263 pthread_mutex_lock(&lock);
1265 EVP_MD_CTX_init(&mdctx);
1270 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1271 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1272 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1275 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1276 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1277 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1278 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1279 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1280 pthread_mutex_unlock(&lock);
1285 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1288 for (i = 0; i < 16; i++)
1291 for (offset = 16; offset < len; offset += 16) {
1293 printf("text + offset - 16 c(%d): ", offset / 16);
1294 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1296 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1297 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1298 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1299 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1301 pthread_mutex_unlock(&lock);
1305 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1308 for (i = 0; i < 16; i++)
1309 text[offset + i] ^= hash[i];
1313 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1316 pthread_mutex_unlock(&lock);
1320 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1321 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1322 static unsigned char first = 1;
1323 static EVP_MD_CTX mdctx;
1324 unsigned char hash[EVP_MAX_MD_SIZE];
1325 unsigned int md_len;
1329 pthread_mutex_lock(&lock);
1331 EVP_MD_CTX_init(&mdctx);
1336 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1337 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1338 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1341 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1342 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1343 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1344 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1345 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1346 pthread_mutex_unlock(&lock);
1351 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1354 for (i = 0; i < 16; i++)
1355 plain[i] = text[i] ^ hash[i];
1357 for (offset = 16; offset < len; offset += 16) {
1359 printf("text + offset - 16 c(%d): ", offset / 16);
1360 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1362 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1363 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1364 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1365 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1367 pthread_mutex_unlock(&lock);
1371 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1374 for (i = 0; i < 16; i++)
1375 plain[offset + i] = text[offset + i] ^ hash[i];
1378 memcpy(text, plain, len);
1380 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1383 pthread_mutex_unlock(&lock);
1387 struct realm *id2realm(char *id, uint8_t len) {
1388 struct list_node *entry;
1389 struct realm *realm;
1391 for (entry = list_first(realms); entry; entry = list_next(entry)) {
1392 realm = (struct realm *)entry->data;
1393 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1394 debug(DBG_DBG, "found matching realm: %s", realm->name);
1401 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1402 struct request *rq = to->requests, *end;
1404 pthread_mutex_lock(&to->newrq_mutex);
1405 for (end = rq + MAX_REQUESTS; rq < end; rq++)
1406 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1408 pthread_mutex_unlock(&to->newrq_mutex);
1413 int attrvalidate(unsigned char *attrs, int length) {
1414 while (length > 1) {
1415 if (ATTRLEN(attrs) < 2) {
1416 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1419 length -= ATTRLEN(attrs);
1421 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1424 attrs += ATTRLEN(attrs);
1427 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1431 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1432 if (len < 16 || len > 128 || len % 16) {
1433 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1437 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1438 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1442 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1444 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1445 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1451 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1454 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1455 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1458 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1459 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1465 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1466 char *oldsecret, char *newsecret) {
1467 unsigned char *attr;
1469 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1470 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1471 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1477 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1481 for (; attrs[0]; attrs += 2)
1482 if (attrs[0] == vendor && attrs[1] == subattr)
1487 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1488 uint8_t alen, sublen, rmlen = 0;
1489 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1492 if (!removevendorattrs)
1495 while (*removevendorattrs && *removevendorattrs != vendor)
1496 removevendorattrs += 2;
1497 if (!*removevendorattrs)
1500 alen = ATTRLEN(attrs);
1502 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1503 /* remove entire vendor attribute */
1504 memmove(attrs, attrs + alen, length - alen);
1509 subattrs = ATTRVAL(attrs) + 4;
1511 if (!attrvalidate(subattrs, sublen)) {
1512 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1517 while (sublen > 1) {
1518 alen = ATTRLEN(subattrs);
1521 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1522 memmove(subattrs, subattrs + alen, length);
1528 ATTRLEN(attrs) -= rmlen;
1532 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1533 uint8_t *attrs, alen;
1534 uint16_t len, rmlen = 0;
1536 if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1539 len = RADLEN(buf) - 20;
1542 alen = ATTRLEN(attrs);
1544 if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1545 memmove(attrs, attrs + alen, len);
1547 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1548 rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1553 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1556 /* returns a pointer to the resized attribute value */
1557 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1558 uint8_t *attrs, *attr, vallen;
1562 len = RADLEN(*buf) - 20;
1565 attr = attrget(attrs, len, type);
1569 vallen = ATTRVALLEN(attr);
1570 if (vallen == newvallen)
1573 len += newvallen - vallen;
1574 if (newvallen > vallen) {
1575 new = realloc(*buf, len + 20);
1577 debug(DBG_ERR, "resizeattr: malloc failed");
1586 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1587 attr[1] = newvallen + 2;
1588 ((uint16_t *)*buf)[1] = htons(len + 20);
1592 int rewriteusername(struct request *rq, char *in) {
1593 size_t nmatch = 10, reslen = 0, start = 0;
1594 regmatch_t pmatch[10], *pfield;
1596 unsigned char *result;
1597 char *out = rq->from->conf->rewriteattrreplacement;
1599 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1600 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1604 rq->origusername = stringcopy(in, 0);
1605 if (!rq->origusername)
1608 for (i = start; out[i]; i++) {
1609 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1610 pfield = &pmatch[out[i + 1] - '0'];
1611 if (pfield->rm_so >= 0) {
1612 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1618 reslen += i - start;
1620 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1626 for (i = start; out[i]; i++) {
1627 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1628 pfield = &pmatch[out[i + 1] - '0'];
1629 if (pfield->rm_so >= 0) {
1630 memcpy(result + reslen, out + start, i - start);
1631 reslen += i - start;
1632 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1633 reslen += pfield->rm_eo - pfield->rm_so;
1640 memcpy(result + reslen, out + start, i - start);
1641 reslen += i - start;
1642 memcpy(in, result, reslen);
1647 const char *radmsgtype2string(uint8_t code) {
1648 static const char *rad_msg_names[] = {
1649 "", "Access-Request", "Access-Accept", "Access-Reject",
1650 "Accounting-Request", "Accounting-Response", "", "",
1651 "", "", "", "Access-Challenge",
1652 "Status-Server", "Status-Client"
1654 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1657 void char2hex(char *h, unsigned char c) {
1658 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1659 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1660 h[0] = hexdigits[c / 16];
1661 h[1] = hexdigits[c % 16];
1665 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
1669 if (!attr || len == 1) {
1674 l = ATTRVALLEN(attr);
1675 s = (char *)ATTRVAL(attr);
1678 for (i = 0; i < l; i++) {
1679 if (s[i] > 31 && s[i] < 127) {
1681 if (d - ascii == len - 1)
1684 if (d - ascii > len - 4)
1689 if (d - ascii == len - 1)
1697 void acclog(unsigned char *attrs, int length, char *host) {
1698 unsigned char *attr;
1701 attr = attrget(attrs, length, RAD_Attr_User_Name);
1703 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1706 radattr2ascii(username, sizeof(username), attr);
1707 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1710 void respondaccounting(struct request *rq) {
1711 unsigned char *resp;
1715 debug(DBG_ERR, "respondstatusserver: malloc failed");
1718 memcpy(resp, rq->buf, 20);
1719 resp[0] = RAD_Accounting_Response;
1722 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1723 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1726 void respondstatusserver(struct request *rq) {
1727 unsigned char *resp;
1731 debug(DBG_ERR, "respondstatusserver: malloc failed");
1734 memcpy(resp, rq->buf, 20);
1735 resp[0] = RAD_Access_Accept;
1738 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1739 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1742 void respondreject(struct request *rq, char *message) {
1743 unsigned char *resp;
1746 if (message && *message)
1747 len += 2 + strlen(message);
1751 debug(DBG_ERR, "respondreject: malloc failed");
1754 memcpy(resp, rq->buf, 20);
1755 resp[0] = RAD_Access_Reject;
1756 *(uint16_t *)(resp + 2) = htons(len);
1757 if (message && *message) {
1758 resp[20] = RAD_Attr_Reply_Message;
1759 resp[21] = len - 20;
1760 memcpy(resp + 22, message, len - 22);
1762 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1765 struct server *chooseserver(struct list *srvconfs) {
1766 struct list_node *entry;
1767 struct server *server, *best = NULL, *first = NULL;
1769 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1770 server = ((struct clsrvconf *)entry->data)->servers;
1773 if (!server->connectionok)
1775 if (!server->lostrqs)
1781 if (server->lostrqs < best->lostrqs)
1784 return best ? best : first;
1787 void radsrv(struct request *rq) {
1788 uint8_t code, id, *auth, *attrs, *attr;
1790 struct server *to = NULL;
1791 char username[254], userascii[760];
1792 unsigned char newauth[16];
1793 struct realm *realm = NULL;
1795 code = *(uint8_t *)rq->buf;
1796 id = *(uint8_t *)(rq->buf + 1);
1797 len = RADLEN(rq->buf);
1798 auth = (uint8_t *)(rq->buf + 4);
1800 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1802 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1803 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1808 attrs = rq->buf + 20;
1810 if (!attrvalidate(attrs, len)) {
1811 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1815 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1816 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
1817 debug(DBG_WARN, "radsrv: message authentication failed");
1821 if (code == RAD_Status_Server) {
1822 respondstatusserver(rq);
1826 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1828 if (code == RAD_Accounting_Request) {
1829 memset(newauth, 0, 16);
1830 if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
1831 debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
1836 if (rq->from->conf->rewrite) {
1837 dorewrite(rq->buf, rq->from->conf->rewrite);
1838 len = RADLEN(rq->buf) - 20;
1841 attr = attrget(attrs, len, RAD_Attr_User_Name);
1843 if (code == RAD_Accounting_Request) {
1844 acclog(attrs, len, rq->from->conf->host);
1845 respondaccounting(rq);
1847 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1850 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1851 username[ATTRVALLEN(attr)] = '\0';
1852 radattr2ascii(userascii, sizeof(userascii), attr);
1854 if (rq->from->conf->rewriteattrregex) {
1855 if (!rewriteusername(rq, username)) {
1856 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1859 len = RADLEN(rq->buf) - 20;
1860 auth = (uint8_t *)(rq->buf + 4);
1861 attrs = rq->buf + 20;
1864 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
1866 realm = id2realm(username, strlen(username));
1868 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1872 to = chooseserver(code == RAD_Access_Request ? realm->srvconfs : realm->accsrvconfs);
1874 if (realm->message && code == RAD_Access_Request) {
1875 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
1876 respondreject(rq, realm->message);
1877 } else if (realm->accresp && code == RAD_Accounting_Request) {
1878 acclog(attrs, len, rq->from->conf->host);
1879 respondaccounting(rq);
1884 if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
1885 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
1886 rq->from->conf->name, to->conf->name);
1890 if (rqinqueue(to, rq->from, id, code)) {
1891 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
1892 radmsgtype2string(code), rq->from->conf->host, id);
1896 if (code != RAD_Accounting_Request) {
1897 if (!RAND_bytes(newauth, 16)) {
1898 debug(DBG_WARN, "radsrv: failed to generate random auth");
1904 printfchars(NULL, "auth", "%02x ", auth, 16);
1907 attr = attrget(attrs, len, RAD_Attr_User_Password);
1909 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1910 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
1914 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1916 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1917 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
1922 memcpy(rq->origauth, auth, 16);
1923 memcpy(auth, newauth, 16);
1931 int replyh(struct server *server, unsigned char *buf) {
1932 struct client *from;
1935 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
1936 struct sockaddr_storage fromsa;
1937 char tmp[760], stationid[760];
1939 server->connectionok = 1;
1940 server->lostrqs = 0;
1942 i = buf[1]; /* i is the id */
1944 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
1945 && *buf != RAD_Accounting_Response) {
1946 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
1949 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
1951 rq = server->requests + i;
1953 pthread_mutex_lock(&server->newrq_mutex);
1954 if (!rq->buf || !rq->tries) {
1955 pthread_mutex_unlock(&server->newrq_mutex);
1956 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
1961 pthread_mutex_unlock(&server->newrq_mutex);
1962 debug(DBG_INFO, "replyh: already received, ignoring reply");
1966 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
1967 pthread_mutex_unlock(&server->newrq_mutex);
1968 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
1972 len = RADLEN(buf) - 20;
1975 if (!attrvalidate(attrs, len)) {
1976 pthread_mutex_unlock(&server->newrq_mutex);
1977 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
1981 /* Message Authenticator */
1982 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1984 if (ATTRVALLEN(messageauth) != 16) {
1985 pthread_mutex_unlock(&server->newrq_mutex);
1986 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
1989 memcpy(tmp, buf + 4, 16);
1990 memcpy(buf + 4, rq->buf + 4, 16);
1991 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
1992 pthread_mutex_unlock(&server->newrq_mutex);
1993 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
1996 memcpy(buf + 4, tmp, 16);
1997 debug(DBG_DBG, "replyh: message auth ok");
2000 if (*rq->buf == RAD_Status_Server) {
2002 pthread_mutex_unlock(&server->newrq_mutex);
2003 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2009 pthread_mutex_unlock(&server->newrq_mutex);
2010 debug(DBG_INFO, "replyh: client gone, ignoring reply");
2014 if (server->conf->rewrite) {
2015 dorewrite(buf, server->conf->rewrite);
2016 len = RADLEN(buf) - 20;
2020 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2021 if (ATTRVALLEN(attr) <= 4)
2024 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
2027 sublen = ATTRVALLEN(attr) - 4;
2028 subattrs = ATTRVAL(attr) + 4;
2029 if (!attrvalidate(subattrs, sublen) ||
2030 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2031 rq, server->conf->secret, from->conf->secret) ||
2032 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2033 rq, server->conf->secret, from->conf->secret))
2037 pthread_mutex_unlock(&server->newrq_mutex);
2038 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2042 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2043 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2045 radattr2ascii(tmp, sizeof(tmp), attr);
2046 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2048 radattr2ascii(stationid, sizeof(stationid), attr);
2049 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2050 radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2052 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2056 buf[1] = (char)rq->origid;
2057 memcpy(buf + 4, rq->origauth, 16);
2059 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2062 if (rq->origusername) {
2063 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2065 pthread_mutex_unlock(&server->newrq_mutex);
2066 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2069 memcpy(username, rq->origusername, strlen(rq->origusername));
2070 len = RADLEN(buf) - 20;
2073 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2077 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2078 pthread_mutex_unlock(&server->newrq_mutex);
2079 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2082 debug(DBG_DBG, "replyh: computed messageauthattr");
2085 if (from->conf->type == 'U')
2086 fromsa = rq->fromsa;
2087 /* once we set received = 1, rq may be reused */
2090 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2091 sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
2092 pthread_mutex_unlock(&server->newrq_mutex);
2096 void *udpclientrd(void *arg) {
2097 struct server *server;
2099 int *s = (int *)arg;
2103 buf = radudpget(*s, NULL, &server, NULL);
2104 if (!replyh(server, buf))
2109 void *tlsclientrd(void *arg) {
2110 struct server *server = (struct server *)arg;
2112 struct timeval lastconnecttry;
2115 /* yes, lastconnecttry is really necessary */
2116 lastconnecttry = server->lastconnecttry;
2117 buf = radtlsget(server->ssl);
2119 tlsconnect(server, &lastconnecttry, "clientrd");
2123 if (!replyh(server, buf))
2128 void *clientwr(void *arg) {
2129 struct server *server = (struct server *)arg;
2131 pthread_t tlsclientrdth;
2134 struct timeval now, lastsend;
2135 struct timespec timeout;
2136 struct request statsrvrq;
2137 unsigned char statsrvbuf[38];
2139 memset(&timeout, 0, sizeof(struct timespec));
2141 if (server->conf->statusserver) {
2142 memset(&statsrvrq, 0, sizeof(struct request));
2143 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2144 statsrvbuf[0] = RAD_Status_Server;
2146 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2147 statsrvbuf[21] = 18;
2148 gettimeofday(&lastsend, NULL);
2151 if (server->conf->type == 'U') {
2152 server->connectionok = 1;
2154 tlsconnect(server, NULL, "new client");
2155 server->connectionok = 1;
2156 if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server))
2157 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
2161 pthread_mutex_lock(&server->newrq_mutex);
2162 if (!server->newrq) {
2163 gettimeofday(&now, NULL);
2164 if (server->conf->statusserver) {
2165 /* random 0-7 seconds */
2166 RAND_bytes(&rnd, 1);
2168 if (!timeout.tv_sec || timeout.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
2169 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
2171 if (timeout.tv_sec) {
2172 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2173 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2176 debug(DBG_DBG, "clientwr: waiting for new request");
2177 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
2180 if (server->newrq) {
2181 debug(DBG_DBG, "clientwr: got new request");
2184 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2185 pthread_mutex_unlock(&server->newrq_mutex);
2187 for (i = 0; i < MAX_REQUESTS; i++) {
2188 pthread_mutex_lock(&server->newrq_mutex);
2189 while (i < MAX_REQUESTS && !server->requests[i].buf)
2191 if (i == MAX_REQUESTS) {
2192 pthread_mutex_unlock(&server->newrq_mutex);
2195 rq = server->requests + i;
2198 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2200 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2202 /* setting this to NULL means that it can be reused */
2205 pthread_mutex_unlock(&server->newrq_mutex);
2209 gettimeofday(&now, NULL);
2210 if (now.tv_sec < rq->expiry.tv_sec) {
2211 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2212 timeout.tv_sec = rq->expiry.tv_sec;
2213 pthread_mutex_unlock(&server->newrq_mutex);
2217 if (rq->tries == (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
2218 ? 1 : server->conf->retrycount + 1)) {
2219 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2220 if (server->conf->statusserver) {
2221 if (*rq->buf == RAD_Status_Server) {
2222 debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->conf->host);
2223 if (server->lostrqs < 255)
2227 debug(DBG_WARN, "clientwr: no server response, %s dead?", server->conf->host);
2228 if (server->lostrqs < 255)
2232 /* setting this to NULL means that it can be reused */
2234 pthread_mutex_unlock(&server->newrq_mutex);
2237 pthread_mutex_unlock(&server->newrq_mutex);
2239 rq->expiry.tv_sec = now.tv_sec +
2240 (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
2241 ? server->conf->retryinterval * (server->conf->retrycount + 1) : server->conf->retryinterval);
2242 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2243 timeout.tv_sec = rq->expiry.tv_sec;
2245 clientradput(server, server->requests[i].buf);
2246 gettimeofday(&lastsend, NULL);
2248 if (server->conf->statusserver) {
2249 gettimeofday(&now, NULL);
2250 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
2251 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2252 debug(DBG_WARN, "clientwr: failed to generate random auth");
2255 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2256 if (!statsrvrq.buf) {
2257 debug(DBG_ERR, "clientwr: malloc failed");
2260 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2261 debug(DBG_DBG, "clientwr: sending status server to %s", server->conf->host);
2262 lastsend.tv_sec = now.tv_sec;
2263 sendrq(server, &statsrvrq);
2269 void *udpserverwr(void *arg) {
2270 struct replyq *replyq = udp_server_replyq;
2271 struct reply *reply;
2274 pthread_mutex_lock(&replyq->mutex);
2275 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2276 debug(DBG_DBG, "udp server writer, waiting for signal");
2277 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2278 debug(DBG_DBG, "udp server writer, got signal");
2280 pthread_mutex_unlock(&replyq->mutex);
2282 if (sendto(*(uint8_t *)reply->buf == RAD_Accounting_Response ? udp_accserver_sock : udp_server_sock,
2283 reply->buf, RADLEN(reply->buf), 0,
2284 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2285 debug(DBG_WARN, "sendudp: send failed");
2291 void *udpserverrd(void *arg) {
2293 pthread_t udpserverwrth;
2294 struct clsrvconf *listenres;
2296 listenres = resolve_hostport('U', options.listenudp, DEFAULT_UDP_PORT);
2297 if ((udp_server_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2298 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2300 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
2301 listenres->host ? listenres->host : "*", listenres->port);
2302 freeclsrvres(listenres);
2304 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
2305 debugx(1, DBG_ERR, "pthread_create failed");
2308 memset(&rq, 0, sizeof(struct request));
2309 rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
2314 void *udpaccserverrd(void *arg) {
2316 struct clsrvconf *listenres;
2318 listenres = resolve_hostport('U', options.listenaccudp, DEFAULT_UDP_PORT);
2319 if ((udp_accserver_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2320 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2322 debug(DBG_WARN, "udpaccserverrd: listening for UDP on %s:%s",
2323 listenres->host ? listenres->host : "*", listenres->port);
2324 freeclsrvres(listenres);
2327 memset(&rq, 0, sizeof(struct request));
2328 rq.buf = radudpget(udp_accserver_sock, &rq.from, NULL, &rq.fromsa);
2329 if (*rq.buf == RAD_Accounting_Request || *rq.buf == RAD_Status_Server) {
2333 debug(DBG_INFO, "udpaccserverrd: accepting only accounting-request and status-server, ignoring");
2338 void *tlsserverwr(void *arg) {
2340 unsigned long error;
2341 struct client *client = (struct client *)arg;
2342 struct replyq *replyq;
2343 struct reply *reply;
2345 debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
2346 replyq = client->replyq;
2348 pthread_mutex_lock(&replyq->mutex);
2349 while (!list_first(replyq->replies)) {
2351 debug(DBG_DBG, "tls server writer, waiting for signal");
2352 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2353 debug(DBG_DBG, "tls server writer, got signal");
2356 /* ssl might have changed while waiting */
2357 pthread_mutex_unlock(&replyq->mutex);
2358 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2359 ERR_remove_state(0);
2363 reply = (struct reply *)list_shift(replyq->replies);
2364 pthread_mutex_unlock(&replyq->mutex);
2365 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2367 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
2368 cnt, RADLEN(reply->buf));
2370 while ((error = ERR_get_error()))
2371 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2377 void tlsserverrd(struct client *client) {
2379 pthread_t tlsserverwrth;
2381 debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2383 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2384 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2389 memset(&rq, 0, sizeof(struct request));
2390 rq.buf = radtlsget(client->ssl);
2393 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2398 debug(DBG_ERR, "tlsserverrd: connection lost");
2399 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2401 pthread_mutex_lock(&client->replyq->mutex);
2402 pthread_cond_signal(&client->replyq->cond);
2403 pthread_mutex_unlock(&client->replyq->mutex);
2404 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2405 pthread_join(tlsserverwrth, NULL);
2406 removeclientrqs(client);
2407 debug(DBG_DBG, "tlsserverrd for %s exiting", client->conf->host);
2410 void *tlsservernew(void *arg) {
2412 struct sockaddr_storage from;
2413 size_t fromlen = sizeof(from);
2414 struct clsrvconf *conf;
2415 struct list_node *cur = NULL;
2418 unsigned long error;
2419 struct client *client;
2422 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
2423 debug(DBG_DBG, "tlsserverrd: getpeername failed, exiting");
2426 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2428 conf = find_conf('T', (struct sockaddr *)&from, clconfs, &cur);
2430 ssl = SSL_new(conf->ssl_ctx);
2433 if (SSL_accept(ssl) <= 0) {
2434 while ((error = ERR_get_error()))
2435 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2436 debug(DBG_ERR, "SSL_accept failed");
2439 cert = verifytlscert(ssl);
2445 if (verifyconfcert(cert, conf)) {
2447 client = addclient(conf);
2450 tlsserverrd(client);
2451 removeclient(client);
2453 debug(DBG_WARN, "Failed to create new client instance");
2456 conf = find_conf('T', (struct sockaddr *)&from, clconfs, &cur);
2458 debug(DBG_WARN, "ignoring request, no matching TLS client");
2465 ERR_remove_state(0);
2466 shutdown(s, SHUT_RDWR);
2472 pthread_t tlsserverth;
2474 struct sockaddr_storage from;
2475 size_t fromlen = sizeof(from);
2476 struct clsrvconf *listenres;
2478 listenres = resolve_hostport('T', options.listentcp, DEFAULT_TLS_PORT);
2479 if ((s = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2480 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
2482 debug(DBG_WARN, "listening for incoming TCP on %s:%s", listenres->host ? listenres->host : "*", listenres->port);
2483 freeclsrvres(listenres);
2487 snew = accept(s, (struct sockaddr *)&from, &fromlen);
2489 debug(DBG_WARN, "accept failed");
2492 if (pthread_create(&tlsserverth, NULL, tlsservernew, (void *)&snew)) {
2493 debug(DBG_ERR, "tlslistener: pthread_create failed");
2494 shutdown(snew, SHUT_RDWR);
2498 pthread_detach(tlsserverth);
2503 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd, uint8_t crlcheck) {
2506 STACK_OF(X509_NAME) *calist;
2509 unsigned long error;
2511 if (!certfile || !certkeyfile)
2512 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2514 if (!cacertfile && !cacertpath)
2515 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2518 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2519 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2520 for (i = 0; i < CRYPTO_num_locks(); i++) {
2521 ssl_lock_count[i] = 0;
2522 pthread_mutex_init(&ssl_locks[i], NULL);
2524 CRYPTO_set_id_callback(ssl_thread_id);
2525 CRYPTO_set_locking_callback(ssl_locking_callback);
2527 SSL_load_error_strings();
2530 while (!RAND_status()) {
2531 time_t t = time(NULL);
2532 pid_t pid = getpid();
2533 RAND_seed((unsigned char *)&t, sizeof(time_t));
2534 RAND_seed((unsigned char *)&pid, sizeof(pid));
2537 ctx = SSL_CTX_new(TLSv1_method());
2539 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2540 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2542 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2543 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2544 !SSL_CTX_check_private_key(ctx) ||
2545 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2546 while ((error = ERR_get_error()))
2547 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2548 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2551 calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
2552 if (!cacertfile || calist) {
2555 calist = sk_X509_NAME_new_null();
2556 if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
2557 sk_X509_NAME_free(calist);
2563 while ((error = ERR_get_error()))
2564 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2565 debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
2567 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2568 SSL_CTX_set_client_CA_list(ctx, calist);
2570 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2571 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2574 x509_s = SSL_CTX_get_cert_store(ctx);
2575 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2578 new = malloc(sizeof(struct tls));
2579 if (!new || !list_push(tlsconfs, new))
2580 debugx(1, DBG_ERR, "malloc failed");
2582 memset(new, 0, sizeof(struct tls));
2583 new->name = stringcopy(value, 0);
2585 debugx(1, DBG_ERR, "malloc failed");
2588 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2592 struct list_node *entry;
2595 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2596 t = (struct tls *)entry->data;
2600 SSL_CTX_free(t->ctx);
2602 list_destroy(tlsconfs);
2606 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2607 struct list_node *entry;
2608 struct tls *t, *t1 = NULL, *t2 = NULL;
2610 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2611 t = (struct tls *)entry->data;
2612 if (!strcasecmp(t->name, alt1)) {
2616 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2627 struct list *addsrvconfs(char *value, char **names) {
2628 struct list *conflist;
2630 struct list_node *entry;
2631 struct clsrvconf *conf = NULL;
2633 if (!names || !*names)
2636 conflist = list_create();
2638 debugx(1, DBG_ERR, "malloc failed");
2640 for (n = 0; names[n]; n++) {
2641 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2642 conf = (struct clsrvconf *)entry->data;
2643 if (!strcasecmp(names[n], conf->name))
2647 debugx(1, DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2649 if (!list_push(conflist, conf))
2650 debugx(1, DBG_ERR, "malloc failed");
2651 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2657 void addrealm(char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2659 struct realm *realm;
2660 char *s, *regex = NULL;
2662 if (*value == '/') {
2663 /* regexp, remove optional trailing / if present */
2664 if (value[strlen(value) - 1] == '/')
2665 value[strlen(value) - 1] = '\0';
2667 /* not a regexp, let us make it one */
2668 if (*value == '*' && !value[1])
2669 regex = stringcopy(".*", 0);
2671 for (n = 0, s = value; *s;)
2674 regex = malloc(strlen(value) + n + 3);
2677 for (n = 1, s = value; *s; s++) {
2687 debugx(1, DBG_ERR, "malloc failed");
2688 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2691 realm = malloc(sizeof(struct realm));
2693 debugx(1, DBG_ERR, "malloc failed");
2695 memset(realm, 0, sizeof(struct realm));
2696 realm->name = stringcopy(value, 0);
2698 debugx(1, DBG_ERR, "malloc failed");
2699 if (message && strlen(message) > 253)
2700 debugx(1, DBG_ERR, "ReplyMessage can be at most 253 bytes");
2701 realm->message = message;
2702 realm->accresp = accresp;
2704 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB))
2705 debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2709 realm->srvconfs = addsrvconfs(value, servers);
2710 realm->accsrvconfs = addsrvconfs(value, accservers);
2712 if (!list_push(realms, realm))
2713 debugx(1, DBG_ERR, "malloc failed");
2714 debug(DBG_DBG, "addrealm: added realm %s", value);
2717 int addmatchcertattr(struct clsrvconf *conf, char *matchcertattr) {
2721 if (!strncasecmp(matchcertattr, "CN:/", 4)) {
2722 r = &conf->certcnregex;
2723 v = matchcertattr + 4;
2724 } else if (!strncasecmp(matchcertattr, "SubjectAltName:URI:/", 20)) {
2725 r = &conf->certuriregex;
2726 v = matchcertattr + 20;
2731 /* regexp, remove optional trailing / if present */
2732 if (v[strlen(v) - 1] == '/')
2733 v[strlen(v) - 1] = '\0';
2737 *r = malloc(sizeof(regex_t));
2739 debug(DBG_ERR, "malloc failed");
2742 if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2745 debug(DBG_ERR, "failed to compile regular expression %s", v);
2751 int addrewriteattr(struct clsrvconf *conf, char *rewriteattr) {
2754 v = rewriteattr + 11;
2755 if (strncasecmp(rewriteattr, "User-Name:/", 11) || !*v)
2757 /* regexp, remove optional trailing / if present */
2758 if (v[strlen(v) - 1] == '/')
2759 v[strlen(v) - 1] = '\0';
2767 conf->rewriteattrregex = malloc(sizeof(regex_t));
2768 if (!conf->rewriteattrregex) {
2769 debug(DBG_ERR, "malloc failed");
2773 conf->rewriteattrreplacement = stringcopy(w, 0);
2774 if (!conf->rewriteattrreplacement) {
2775 free(conf->rewriteattrregex);
2776 conf->rewriteattrregex = NULL;
2780 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
2781 free(conf->rewriteattrregex);
2782 conf->rewriteattrregex = NULL;
2783 free(conf->rewriteattrreplacement);
2784 conf->rewriteattrreplacement = NULL;
2785 debug(DBG_ERR, "failed to compile regular expression %s", v);
2792 /* should accept both names and numeric values, only numeric right now */
2793 uint8_t attrname2val(char *attrname) {
2796 val = atoi(attrname);
2797 return val > 0 && val < 256 ? val : 0;
2800 /* should accept both names and numeric values, only numeric right now */
2801 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2804 *vendor = atoi(attrname);
2805 s = strchr(attrname, ':');
2810 *type = atoi(s + 1);
2811 return *type >= 0 && *type < 256;
2814 void rewritefree() {
2815 struct list_node *entry;
2816 struct rewriteconf *r;
2818 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
2819 r = (struct rewriteconf *)entry->data;
2825 list_destroy(rewriteconfs);
2826 rewriteconfs = NULL;
2829 struct rewrite *getrewrite(char *alt1, char *alt2) {
2830 struct list_node *entry;
2831 struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
2833 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
2834 r = (struct rewriteconf *)entry->data;
2835 if (!strcasecmp(r->name, alt1)) {
2839 if (!r2 && alt2 && !strcasecmp(r->name, alt2))
2850 void addrewrite(char *value, char **attrs, char **vattrs) {
2851 struct rewriteconf *new;
2852 struct rewrite *rewrite = NULL;
2855 uint32_t *p, *va = NULL;
2859 for (; attrs[n]; n++);
2860 a = malloc((n + 1) * sizeof(uint8_t));
2862 debugx(1, DBG_ERR, "malloc failed");
2864 for (i = 0; i < n; i++) {
2865 if (!(a[i] = attrname2val(attrs[i])))
2866 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
2875 for (; vattrs[n]; n++);
2876 va = malloc((2 * n + 1) * sizeof(uint32_t));
2878 debugx(1, DBG_ERR, "malloc failed");
2880 for (p = va, i = 0; i < n; i++, p += 2) {
2881 if (!vattrname2val(vattrs[i], p, p + 1))
2882 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
2890 rewrite = malloc(sizeof(struct rewrite));
2892 debugx(1, DBG_ERR, "malloc failed");
2893 rewrite->removeattrs = a;
2894 rewrite->removevendorattrs = va;
2897 new = malloc(sizeof(struct rewriteconf));
2898 if (!new || !list_push(rewriteconfs, new))
2899 debugx(1, DBG_ERR, "malloc failed");
2901 memset(new, 0, sizeof(struct rewriteconf));
2902 new->name = stringcopy(value, 0);
2904 debugx(1, DBG_ERR, "malloc failed");
2906 new->rewrite = rewrite;
2907 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2910 void confclient_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2911 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *rewrite = NULL, *rewriteattr = NULL;
2912 struct clsrvconf *conf;
2914 debug(DBG_DBG, "confclient_cb called for %s", block);
2916 conf = malloc(sizeof(struct clsrvconf));
2917 if (!conf || !list_push(clconfs, conf))
2918 debugx(1, DBG_ERR, "malloc failed");
2919 memset(conf, 0, sizeof(struct clsrvconf));
2920 conf->certnamecheck = 1;
2922 getgenericconfig(cf, block,
2923 "type", CONF_STR, &type,
2924 "host", CONF_STR, &conf->host,
2925 "secret", CONF_STR, &conf->secret,
2926 "tls", CONF_STR, &tls,
2927 "matchcertificateattribute", CONF_STR, &matchcertattr,
2928 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2929 "rewrite", CONF_STR, &rewrite,
2930 "rewriteattribute", CONF_STR, &rewriteattr,
2934 conf->name = stringcopy(val, 0);
2936 conf->host = stringcopy(val, 0);
2938 if (type && !strcasecmp(type, "udp")) {
2941 } else if (type && !strcasecmp(type, "tls")) {
2942 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultclient", "default");
2944 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2945 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2946 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2950 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2955 free(matchcertattr);
2957 conf->rewrite = rewrite ? getrewrite(rewrite, NULL) : getrewrite("defaultclient", "default");
2960 if (!addrewriteattr(conf, rewriteattr))
2961 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2965 if (!resolvepeer(conf, 0))
2966 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2968 if (!conf->secret) {
2969 if (conf->type == 'U')
2970 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2971 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2975 void confserver_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2976 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *rewrite = NULL;
2977 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
2978 struct clsrvconf *conf;
2980 debug(DBG_DBG, "confserver_cb called for %s", block);
2982 conf = malloc(sizeof(struct clsrvconf));
2983 if (!conf || !list_push(srvconfs, conf))
2984 debugx(1, DBG_ERR, "malloc failed");
2985 memset(conf, 0, sizeof(struct clsrvconf));
2986 conf->certnamecheck = 1;
2988 getgenericconfig(cf, block,
2989 "type", CONF_STR, &type,
2990 "host", CONF_STR, &conf->host,
2991 "port", CONF_STR, &conf->port,
2992 "secret", CONF_STR, &conf->secret,
2993 "tls", CONF_STR, &tls,
2994 "MatchCertificateAttribute", CONF_STR, &matchcertattr,
2995 "rewrite", CONF_STR, &rewrite,
2996 "StatusServer", CONF_BLN, &conf->statusserver,
2997 "RetryInterval", CONF_LINT, &retryinterval,
2998 "RetryCount", CONF_LINT, &retrycount,
2999 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3003 conf->name = stringcopy(val, 0);
3005 conf->host = stringcopy(val, 0);
3007 if (type && !strcasecmp(type, "udp")) {
3010 conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
3011 } else if (type && !strcasecmp(type, "tls")) {
3012 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultserver", "default");
3014 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3015 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
3016 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3018 conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
3021 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
3026 free(matchcertattr);
3028 if (retryinterval != LONG_MIN) {
3029 if (retryinterval < 1 || retryinterval > 60)
3030 debugx(1, DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-60", block, retryinterval);
3031 conf->retryinterval = (uint8_t)retryinterval;
3033 conf->retryinterval = REQUEST_RETRY_INTERVAL;
3035 if (retrycount != LONG_MIN) {
3036 if (retrycount < 0 || retrycount > 10)
3037 debugx(1, DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-10", block, retrycount);
3038 conf->retrycount = (uint8_t)retrycount;
3040 conf->retrycount = REQUEST_RETRY_COUNT;
3042 conf->rewrite = rewrite ? getrewrite(rewrite, NULL) : getrewrite("defaultserver", "default");
3044 if (!resolvepeer(conf, 0))
3045 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3047 if (!conf->secret) {
3048 if (conf->type == 'U')
3049 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
3050 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
3054 void confrealm_cb(struct gconffile **cf, char *block, char *opt, char *val) {
3055 char **servers = NULL, **accservers = NULL, *msg = NULL;
3056 uint8_t accresp = 0;
3058 debug(DBG_DBG, "confrealm_cb called for %s", block);
3060 getgenericconfig(cf, block,
3061 "server", CONF_MSTR, &servers,
3062 "accountingServer", CONF_MSTR, &accservers,
3063 "ReplyMessage", CONF_STR, &msg,
3064 "AccountingResponse", CONF_BLN, &accresp,
3068 addrealm(val, servers, accservers, msg, accresp);
3071 void conftls_cb(struct gconffile **cf, char *block, char *opt, char *val) {
3072 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
3073 uint8_t crlcheck = 0;
3075 debug(DBG_DBG, "conftls_cb called for %s", block);
3077 getgenericconfig(cf, block,
3078 "CACertificateFile", CONF_STR, &cacertfile,
3079 "CACertificatePath", CONF_STR, &cacertpath,
3080 "CertificateFile", CONF_STR, &certfile,
3081 "CertificateKeyFile", CONF_STR, &certkeyfile,
3082 "CertificateKeyPassword", CONF_STR, &certkeypwd,
3083 "CRLCheck", CONF_BLN, &crlcheck,
3087 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd, crlcheck);
3095 void confrewrite_cb(struct gconffile **cf, char *block, char *opt, char *val) {
3096 char **attrs = NULL, **vattrs = NULL;
3098 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3100 getgenericconfig(cf, block,
3101 "removeAttribute", CONF_MSTR, &attrs,
3102 "removeVendorAttribute", CONF_MSTR, &vattrs,
3105 addrewrite(val, attrs, vattrs);
3108 void getmainconfig(const char *configfile) {
3109 long int loglevel = LONG_MIN;
3110 struct gconffile *cfs;
3112 cfs = openconfigfile(configfile);
3113 memset(&options, 0, sizeof(options));
3115 clconfs = list_create();
3117 debugx(1, DBG_ERR, "malloc failed");
3119 srvconfs = list_create();
3121 debugx(1, DBG_ERR, "malloc failed");
3123 realms = list_create();
3125 debugx(1, DBG_ERR, "malloc failed");
3127 tlsconfs = list_create();
3129 debugx(1, DBG_ERR, "malloc failed");
3131 rewriteconfs = list_create();
3133 debugx(1, DBG_ERR, "malloc failed");
3135 getgenericconfig(&cfs, NULL,
3136 "ListenUDP", CONF_STR, &options.listenudp,
3137 "ListenTCP", CONF_STR, &options.listentcp,
3138 "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
3139 "SourceUDP", CONF_STR, &options.sourceudp,
3140 "SourceTCP", CONF_STR, &options.sourcetcp,
3141 "LogLevel", CONF_LINT, &loglevel,
3142 "LogDestination", CONF_STR, &options.logdestination,
3143 "LoopPrevention", CONF_BLN, &options.loopprevention,
3144 "Client", CONF_CBK, confclient_cb,
3145 "Server", CONF_CBK, confserver_cb,
3146 "Realm", CONF_CBK, confrealm_cb,
3147 "TLS", CONF_CBK, conftls_cb,
3148 "Rewrite", CONF_CBK, confrewrite_cb,
3154 if (loglevel != LONG_MIN) {
3155 if (loglevel < 1 || loglevel > 4)
3156 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3157 options.loglevel = (uint8_t)loglevel;
3161 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3164 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3167 *configfile = optarg;
3170 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3171 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3172 *loglevel = *optarg - '0';
3181 debugx(0, DBG_ERR, "radsecproxy 1.1");
3186 if (!(argc - optind))
3190 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3194 int daemon(int a, int b) {
3202 for (i = 0; i < 3; i++) {
3204 open("/dev/null", O_RDWR);
3210 void *sighandler(void *arg) {
3215 sigemptyset(&sigset);
3216 sigaddset(&sigset, SIGPIPE);
3217 sigwait(&sigset, &sig);
3218 /* only get SIGPIPE right now, so could simplify below code */
3221 /* completely ignoring this */
3224 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3227 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3232 int main(int argc, char **argv) {
3233 pthread_t sigth, udpserverth, udpaccserverth, udpclient4rdth, udpclient6rdth;
3235 struct list_node *entry;
3236 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3237 char *configfile = NULL;
3239 debug_init("radsecproxy");
3240 debug_set_level(DEBUG_LEVEL);
3241 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3243 debug_set_level(loglevel);
3244 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3246 options.loglevel = loglevel;
3247 else if (options.loglevel)
3248 debug_set_level(options.loglevel);
3250 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3251 free(options.logdestination);
3253 if (!list_first(clconfs))
3254 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3255 if (!list_first(srvconfs))
3256 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
3257 if (!list_first(realms))
3258 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3261 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3263 if (!foreground && (daemon(0, 0) < 0))
3264 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3266 debug(DBG_INFO, "radsecproxy 1.1 starting");
3268 sigemptyset(&sigset);
3269 /* exit on all but SIGPIPE, ignore more? */
3270 sigaddset(&sigset, SIGPIPE);
3271 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3272 pthread_create(&sigth, NULL, sighandler, NULL);
3274 if (client_udp_count) {
3275 udp_server_replyq = newreplyq();
3276 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
3277 debugx(1, DBG_ERR, "pthread_create failed");
3278 if (options.listenaccudp)
3279 if (pthread_create(&udpaccserverth, NULL, udpaccserverrd, NULL))
3280 debugx(1, DBG_ERR, "pthread_create failed");
3283 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3284 addserver((struct clsrvconf *)entry->data);
3285 if (pthread_create(&((struct clsrvconf *)entry->data)->servers->clientth, NULL, clientwr,
3286 (void *)((struct clsrvconf *)entry->data)->servers))
3287 debugx(1, DBG_ERR, "pthread_create failed");
3289 /* srcudpres no longer needed, while srctcpres is needed later */
3291 freeaddrinfo(srcudpres);
3294 if (udp_client4_sock >= 0)
3295 if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
3296 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
3297 if (udp_client6_sock >= 0)
3298 if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
3299 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
3301 if (client_tls_count)
3302 return tlslistener();
3304 /* just hang around doing nothing, anything to do here? */