2 * Copyright (C) 2006, 2007 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
32 #include <sys/socket.h>
33 #include <netinet/in.h>
38 #include <sys/types.h>
39 #include <arpa/inet.h>
43 #include <openssl/ssl.h>
44 #include <openssl/rand.h>
45 #include <openssl/err.h>
46 #include <openssl/md5.h>
47 #include <openssl/hmac.h>
48 #include <openssl/x509v3.h>
51 #include "radsecproxy.h"
53 static struct options options;
54 struct list *clconfs, *srvconfs, *realms, *tlsconfs;
56 static int client_udp_count = 0;
57 static int client_tls_count = 0;
58 static int server_udp_count = 0;
59 static int server_tls_count = 0;
61 static struct clsrvconf *tcp_server_listen;
62 static struct clsrvconf *udp_server_listen;
63 static struct clsrvconf *udp_accserver_listen;
64 static struct replyq *udp_server_replyq = NULL;
65 static int udp_server_sock = -1;
66 static int udp_accserver_sock = -1;
67 static pthread_mutex_t *ssl_locks;
68 static long *ssl_lock_count;
72 /* callbacks for making OpenSSL thread safe */
73 unsigned long ssl_thread_id() {
74 return (unsigned long)pthread_self();
77 void ssl_locking_callback(int mode, int type, const char *file, int line) {
78 if (mode & CRYPTO_LOCK) {
79 pthread_mutex_lock(&ssl_locks[type]);
80 ssl_lock_count[type]++;
82 pthread_mutex_unlock(&ssl_locks[type]);
85 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
86 int pwdlen = strlen(userdata);
87 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
89 memcpy(buf, userdata, pwdlen);
93 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
98 err_cert = X509_STORE_CTX_get_current_cert(ctx);
99 err = X509_STORE_CTX_get_error(ctx);
100 depth = X509_STORE_CTX_get_error_depth(ctx);
102 if (depth > MAX_CERT_DEPTH) {
104 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
105 X509_STORE_CTX_set_error(ctx, err);
109 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
110 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
113 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
114 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
115 debug(DBG_WARN, "\tIssuer=%s", buf);
117 case X509_V_ERR_CERT_NOT_YET_VALID:
118 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
119 debug(DBG_WARN, "\tCertificate not yet valid");
121 case X509_V_ERR_CERT_HAS_EXPIRED:
122 debug(DBG_WARN, "Certificate has expired");
124 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
125 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
130 printf("certificate verify returns %d\n", ok);
135 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
136 struct addrinfo hints, *addrinfo;
140 slash = conf->host ? strchr(conf->host, '/') : NULL;
144 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
148 if (*s < '0' || *s > '9') {
149 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
152 plen = atoi(slash + 1);
153 if (plen < 0 || plen > 128) {
154 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
159 memset(&hints, 0, sizeof(hints));
160 hints.ai_socktype = (conf->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
161 hints.ai_family = AF_UNSPEC;
162 hints.ai_flags = ai_flags;
164 hints.ai_flags |= AI_NUMERICHOST;
165 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
166 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host, conf->port);
172 switch (addrinfo->ai_family) {
175 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
176 freeaddrinfo(addrinfo);
183 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
184 freeaddrinfo(addrinfo);
187 conf->prefixlen = plen;
189 conf->prefixlen = 255;
192 freeaddrinfo(conf->addrinfo);
193 conf->addrinfo = addrinfo;
197 int connecttoserver(struct addrinfo *addrinfo) {
199 struct addrinfo *res;
202 for (res = addrinfo; res; res = res->ai_next) {
203 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
205 debug(DBG_WARN, "connecttoserver: socket failed");
208 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
210 debug(DBG_WARN, "connecttoserver: connect failed");
217 int bindtoaddr(struct addrinfo *addrinfo) {
219 struct addrinfo *res;
221 for (res = addrinfo; res; res = res->ai_next) {
222 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
224 debug(DBG_WARN, "bindtoaddr: socket failed");
227 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
228 if (!bind(s, res->ai_addr, res->ai_addrlen))
230 debug(DBG_WARN, "bindtoaddr: bind failed");
236 /* returns 1 if the len first bits are equal, else 0 */
237 int prefixmatch(void *a1, void *a2, uint8_t len) {
238 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
240 if (l && memcmp(a1, a2, l))
245 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
248 /* returns the config with matching address, or NULL */
249 /* if conf argument is not NULL, we only check that one */
250 struct clsrvconf *find_conf(char type, struct sockaddr *addr, struct list *confs, struct clsrvconf *conf) {
251 struct sockaddr_in6 *sa6 = NULL;
252 struct in_addr *a4 = NULL;
253 struct addrinfo *res;
254 struct list_node *entry;
256 if (addr->sa_family == AF_INET6) {
257 sa6 = (struct sockaddr_in6 *)addr;
258 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
259 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
263 a4 = &((struct sockaddr_in *)addr)->sin_addr;
266 if (conf->type == type) {
267 if (conf->prefixlen == 255) {
268 for (res = conf->addrinfo; res; res = res->ai_next)
269 if ((a4 && res->ai_family == AF_INET &&
270 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
271 (sa6 && res->ai_family == AF_INET6 &&
272 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
275 res = conf->addrinfo;
277 ((a4 && res->ai_family == AF_INET &&
278 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
279 (sa6 && res->ai_family == AF_INET6 &&
280 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
287 for (entry = list_first(confs); entry; entry = list_next(entry)) {
288 conf = (struct clsrvconf *)entry->data;
289 if (conf->type == type) {
290 if (conf->prefixlen == 255) {
291 for (res = conf->addrinfo; res; res = res->ai_next)
292 if ((a4 && res->ai_family == AF_INET &&
293 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
294 (sa6 && res->ai_family == AF_INET6 &&
295 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
298 res = conf->addrinfo;
300 ((a4 && res->ai_family == AF_INET &&
301 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
302 (sa6 && res->ai_family == AF_INET6 &&
303 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
311 struct replyq *newreplyq() {
312 struct replyq *replyq;
314 replyq = malloc(sizeof(struct replyq));
316 debugx(1, DBG_ERR, "malloc failed");
317 replyq->replies = list_create();
318 if (!replyq->replies)
319 debugx(1, DBG_ERR, "malloc failed");
320 pthread_mutex_init(&replyq->mutex, NULL);
321 pthread_cond_init(&replyq->cond, NULL);
325 struct client *addclient(struct clsrvconf *conf) {
326 struct client *new = malloc(sizeof(struct client));
329 debug(DBG_ERR, "malloc failed");
332 if (!conf->clients) {
333 conf->clients = list_create();
334 if (!conf->clients) {
335 debug(DBG_ERR, "malloc failed");
340 memset(new, 0, sizeof(struct client));
342 new->replyq = conf->type == 'T' ? newreplyq() : udp_server_replyq;
344 list_push(conf->clients, new);
348 void removeclient(struct client *client) {
349 if (!client || !client->conf->clients)
352 list_removedata(client->conf->clients, client);
356 void addserver(struct clsrvconf *conf) {
358 debugx(1, DBG_ERR, "currently works with just one server per conf");
360 conf->servers = malloc(sizeof(struct server));
362 debugx(1, DBG_ERR, "malloc failed");
363 memset(conf->servers, 0, sizeof(struct server));
364 conf->servers->conf = conf;
366 conf->servers->sock = -1;
367 pthread_mutex_init(&conf->servers->lock, NULL);
368 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
369 if (!conf->servers->requests)
370 debugx(1, DBG_ERR, "malloc failed");
371 conf->servers->newrq = 0;
372 pthread_mutex_init(&conf->servers->newrq_mutex, NULL);
373 pthread_cond_init(&conf->servers->newrq_cond, NULL);
376 /* exactly one of client and server must be non-NULL */
377 /* should probably take peer list (client(s) or server(s)) as argument instead */
378 /* if *peer == NULL we return who we received from, else require it to be from peer */
379 /* return from in sa if not NULL */
380 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
382 unsigned char buf[65536], *rad;
383 struct sockaddr_storage from;
384 socklen_t fromlen = sizeof(from);
386 struct list_node *node;
389 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
391 debug(DBG_WARN, "radudpget: recv failed");
394 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
397 debug(DBG_WARN, "radudpget: packet too small");
403 debug(DBG_WARN, "radudpget: length too small");
408 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
412 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
416 p = find_conf('U', (struct sockaddr *)&from, NULL, (*client)->conf);
418 p = find_conf('U', (struct sockaddr *)&from, clconfs, NULL);
421 p = find_conf('U', (struct sockaddr *)&from, NULL, (*server)->conf);
423 p = find_conf('U', (struct sockaddr *)&from, srvconfs, NULL);
426 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer, ignoring");
432 debug(DBG_ERR, "radudpget: malloc failed");
436 if (client && !*client) {
437 node = list_first(p->clients);
438 *client = node ? (struct client *)node->data : addclient(p);
443 } else if (server && !*server)
444 *server = p->servers;
448 memcpy(rad, buf, len);
454 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
455 int loc, i, l, n, r = 0;
458 STACK_OF(GENERAL_NAME) *alt;
461 debug(DBG_DBG, "subjectaltnameaddr");
463 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
467 ex = X509_get_ext(cert, loc);
468 alt = X509V3_EXT_d2i(ex);
472 n = sk_GENERAL_NAME_num(alt);
473 for (i = 0; i < n; i++) {
474 gn = sk_GENERAL_NAME_value(alt, i);
475 if (gn->type != GEN_IPADD)
478 v = (char *)ASN1_STRING_data(gn->d.ia5);
479 l = ASN1_STRING_length(gn->d.ia5);
480 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
481 && !memcmp(v, &addr, l)) {
486 GENERAL_NAMES_free(alt);
490 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
491 int loc, i, l, n, r = 0;
494 STACK_OF(GENERAL_NAME) *alt;
497 debug(DBG_DBG, "subjectaltnameregexp");
499 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
503 ex = X509_get_ext(cert, loc);
504 alt = X509V3_EXT_d2i(ex);
508 n = sk_GENERAL_NAME_num(alt);
509 for (i = 0; i < n; i++) {
510 gn = sk_GENERAL_NAME_value(alt, i);
511 if (gn->type != type)
514 v = (char *)ASN1_STRING_data(gn->d.ia5);
515 l = ASN1_STRING_length(gn->d.ia5);
519 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
522 if (memcmp(v, exact, l))
525 s = stringcopy((char *)v, l);
527 debug(DBG_ERR, "malloc failed");
530 if (regexec(regex, s, 0, NULL, 0)) {
539 GENERAL_NAMES_free(alt);
543 int tlsverifycert(SSL *ssl, struct clsrvconf *conf) {
550 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
552 struct in6_addr addr;
554 if (SSL_get_verify_result(ssl) != X509_V_OK) {
555 debug(DBG_ERR, "tlsverifycert: basic validation failed");
556 while ((error = ERR_get_error()))
557 debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
561 cert = SSL_get_peer_certificate(ssl);
563 debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
567 if (inet_pton(AF_INET, conf->host, &addr))
569 else if (inet_pton(AF_INET6, conf->host, &addr))
572 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
576 debug(DBG_DBG, "tlsverifycert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
579 debug(DBG_DBG, "tlsverifycert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
581 nm = X509_get_subject_name(cert);
584 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
587 e = X509_NAME_get_entry(nm, loc);
588 s = X509_NAME_ENTRY_get_data(e);
589 v = (char *) ASN1_STRING_data(s);
590 l = ASN1_STRING_length(s);
594 printfchars(NULL, "cn", NULL, v, l);
596 if (l == strlen(conf->host) && !strncasecmp(conf->host, v, l)) {
598 debug(DBG_DBG, "tlsverifycert: Found cn matching host %s", conf->host);
604 debug(DBG_ERR, "tlsverifycert: cn not matching host %s", conf->host);
608 if (conf->certuriregex) {
609 r = subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex);
611 debug(DBG_DBG, "tlsverifycert: subjectaltname URI not matching regex");
615 debug(DBG_DBG, "tlsverifycert: subjectaltname URI matching regex");
621 void tlsconnect(struct server *server, struct timeval *when, char *text) {
625 debug(DBG_DBG, "tlsconnect called from %s", text);
626 pthread_mutex_lock(&server->lock);
627 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
628 /* already reconnected, nothing to do */
629 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
630 pthread_mutex_unlock(&server->lock);
634 debug(DBG_DBG, "tlsconnect %s", text);
637 gettimeofday(&now, NULL);
638 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
639 if (server->connectionok) {
640 server->connectionok = 0;
642 } else if (elapsed < 5)
644 else if (elapsed < 300) {
645 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
647 } else if (elapsed < 100000) {
648 debug(DBG_INFO, "tlsconnect: sleeping %ds", 600);
651 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
652 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
653 if (server->sock >= 0)
655 if ((server->sock = connecttoserver(server->conf->addrinfo)) < 0) {
656 debug(DBG_ERR, "tlsconnect: connecttoserver failed");
660 SSL_free(server->ssl);
661 server->ssl = SSL_new(server->conf->ssl_ctx);
662 SSL_set_fd(server->ssl, server->sock);
663 if (SSL_connect(server->ssl) > 0 && tlsverifycert(server->ssl, server->conf))
666 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
667 gettimeofday(&server->lastconnecttry, NULL);
668 pthread_mutex_unlock(&server->lock);
671 unsigned char *radtlsget(SSL *ssl) {
673 unsigned char buf[4], *rad;
676 for (total = 0; total < 4; total += cnt) {
677 cnt = SSL_read(ssl, buf + total, 4 - total);
679 debug(DBG_ERR, "radtlsget: connection lost");
680 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
681 /* remote end sent close_notify, send one back */
691 debug(DBG_ERR, "radtlsget: malloc failed");
696 for (; total < len; total += cnt) {
697 cnt = SSL_read(ssl, rad + total, len - total);
699 debug(DBG_ERR, "radtlsget: connection lost");
700 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
701 /* remote end sent close_notify, send one back */
713 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
716 debug(DBG_DBG, "radtlsget: got %d bytes", total);
720 int clientradput(struct server *server, unsigned char *rad) {
724 struct timeval lastconnecttry;
727 if (server->conf->type == 'U') {
728 if (send(server->sock, rad, len, 0) >= 0) {
729 debug(DBG_DBG, "clienradput: sent UDP of length %d to %s port %s", len, server->conf->host, server->conf->port);
732 debug(DBG_WARN, "clientradput: send failed");
736 lastconnecttry = server->lastconnecttry;
737 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
738 while ((error = ERR_get_error()))
739 debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
740 tlsconnect(server, &lastconnecttry, "clientradput");
741 lastconnecttry = server->lastconnecttry;
744 server->connectionok = 1;
745 debug(DBG_DBG, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s",
746 cnt, len, server->conf->host);
750 int radsign(unsigned char *rad, unsigned char *sec) {
751 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
752 static unsigned char first = 1;
753 static EVP_MD_CTX mdctx;
757 pthread_mutex_lock(&lock);
759 EVP_MD_CTX_init(&mdctx);
763 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
764 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
765 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
766 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
768 pthread_mutex_unlock(&lock);
772 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
773 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
774 static unsigned char first = 1;
775 static EVP_MD_CTX mdctx;
776 unsigned char hash[EVP_MAX_MD_SIZE];
780 pthread_mutex_lock(&lock);
782 EVP_MD_CTX_init(&mdctx);
788 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
789 EVP_DigestUpdate(&mdctx, rad, 4) &&
790 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
791 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
792 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
793 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
795 !memcmp(hash, rad + 4, 16));
796 pthread_mutex_unlock(&lock);
800 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
801 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
802 static unsigned char first = 1;
803 static HMAC_CTX hmacctx;
805 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
807 pthread_mutex_lock(&lock);
809 HMAC_CTX_init(&hmacctx);
813 memcpy(auth, authattr, 16);
814 memset(authattr, 0, 16);
816 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
817 HMAC_Update(&hmacctx, rad, RADLEN(rad));
818 HMAC_Final(&hmacctx, hash, &md_len);
819 memcpy(authattr, auth, 16);
821 debug(DBG_WARN, "message auth computation failed");
822 pthread_mutex_unlock(&lock);
826 if (memcmp(auth, hash, 16)) {
827 debug(DBG_WARN, "message authenticator, wrong value");
828 pthread_mutex_unlock(&lock);
832 pthread_mutex_unlock(&lock);
836 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
837 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
838 static unsigned char first = 1;
839 static HMAC_CTX hmacctx;
845 pthread_mutex_lock(&lock);
847 HMAC_CTX_init(&hmacctx);
851 memset(authattrval, 0, 16);
853 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
854 HMAC_Update(&hmacctx, rad, RADLEN(rad));
855 HMAC_Final(&hmacctx, authattrval, &md_len);
857 debug(DBG_WARN, "message auth computation failed");
858 pthread_mutex_unlock(&lock);
862 pthread_mutex_unlock(&lock);
866 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
868 if (ATTRTYPE(attrs) == type)
870 length -= ATTRLEN(attrs);
871 attrs += ATTRLEN(attrs);
876 void freerqdata(struct request *rq) {
877 if (rq->origusername)
878 free(rq->origusername);
883 void sendrq(struct server *to, struct request *rq) {
887 pthread_mutex_lock(&to->newrq_mutex);
888 /* might simplify if only try nextid, might be ok */
889 for (i = to->nextid; i < MAX_REQUESTS; i++)
890 if (!to->requests[i].buf)
892 if (i == MAX_REQUESTS) {
893 for (i = 0; i < to->nextid; i++)
894 if (!to->requests[i].buf)
896 if (i == to->nextid) {
897 debug(DBG_WARN, "No room in queue, dropping request");
899 pthread_mutex_unlock(&to->newrq_mutex);
904 rq->buf[1] = (char)i;
906 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
907 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
909 pthread_mutex_unlock(&to->newrq_mutex);
913 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
914 to->requests[i] = *rq;
919 debug(DBG_DBG, "signalling client writer");
920 pthread_cond_signal(&to->newrq_cond);
922 pthread_mutex_unlock(&to->newrq_mutex);
925 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
929 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
931 debug(DBG_WARN, "sendreply: failed to sign message");
935 reply = malloc(sizeof(struct reply));
938 debug(DBG_ERR, "sendreply: malloc failed");
941 memset(reply, 0, sizeof(struct reply));
946 pthread_mutex_lock(&to->replyq->mutex);
948 first = list_first(to->replyq->replies) == NULL;
950 if (!list_push(to->replyq->replies, reply)) {
951 pthread_mutex_unlock(&to->replyq->mutex);
954 debug(DBG_ERR, "sendreply: malloc failed");
959 debug(DBG_DBG, "signalling server writer");
960 pthread_cond_signal(&to->replyq->cond);
962 pthread_mutex_unlock(&to->replyq->mutex);
965 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
966 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
967 static unsigned char first = 1;
968 static EVP_MD_CTX mdctx;
969 unsigned char hash[EVP_MAX_MD_SIZE], *input;
971 uint8_t i, offset = 0, out[128];
973 pthread_mutex_lock(&lock);
975 EVP_MD_CTX_init(&mdctx);
981 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
982 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
983 !EVP_DigestUpdate(&mdctx, input, 16) ||
984 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
986 pthread_mutex_unlock(&lock);
989 for (i = 0; i < 16; i++)
990 out[offset + i] = hash[i] ^ in[offset + i];
991 input = out + offset - 16;
996 memcpy(in, out, len);
997 pthread_mutex_unlock(&lock);
1001 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1002 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1003 static unsigned char first = 1;
1004 static EVP_MD_CTX mdctx;
1005 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1006 unsigned int md_len;
1007 uint8_t i, offset = 0, out[128];
1009 pthread_mutex_lock(&lock);
1011 EVP_MD_CTX_init(&mdctx);
1017 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1018 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1019 !EVP_DigestUpdate(&mdctx, input, 16) ||
1020 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1022 pthread_mutex_unlock(&lock);
1025 for (i = 0; i < 16; i++)
1026 out[offset + i] = hash[i] ^ in[offset + i];
1027 input = in + offset;
1032 memcpy(in, out, len);
1033 pthread_mutex_unlock(&lock);
1037 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1038 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1039 static unsigned char first = 1;
1040 static EVP_MD_CTX mdctx;
1041 unsigned char hash[EVP_MAX_MD_SIZE];
1042 unsigned int md_len;
1045 pthread_mutex_lock(&lock);
1047 EVP_MD_CTX_init(&mdctx);
1052 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1053 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1054 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1057 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1058 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1059 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1060 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1061 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1062 pthread_mutex_unlock(&lock);
1067 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1070 for (i = 0; i < 16; i++)
1073 for (offset = 16; offset < len; offset += 16) {
1075 printf("text + offset - 16 c(%d): ", offset / 16);
1076 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1078 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1079 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1080 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1081 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1083 pthread_mutex_unlock(&lock);
1087 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1090 for (i = 0; i < 16; i++)
1091 text[offset + i] ^= hash[i];
1095 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1098 pthread_mutex_unlock(&lock);
1102 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1103 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1104 static unsigned char first = 1;
1105 static EVP_MD_CTX mdctx;
1106 unsigned char hash[EVP_MAX_MD_SIZE];
1107 unsigned int md_len;
1111 pthread_mutex_lock(&lock);
1113 EVP_MD_CTX_init(&mdctx);
1118 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1119 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1120 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1123 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1124 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1125 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1126 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1127 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1128 pthread_mutex_unlock(&lock);
1133 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1136 for (i = 0; i < 16; i++)
1137 plain[i] = text[i] ^ hash[i];
1139 for (offset = 16; offset < len; offset += 16) {
1141 printf("text + offset - 16 c(%d): ", offset / 16);
1142 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1144 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1145 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1146 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1147 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1149 pthread_mutex_unlock(&lock);
1153 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1156 for (i = 0; i < 16; i++)
1157 plain[offset + i] = text[offset + i] ^ hash[i];
1160 memcpy(text, plain, len);
1162 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1165 pthread_mutex_unlock(&lock);
1169 struct realm *id2realm(char *id, uint8_t len) {
1170 struct list_node *entry;
1171 struct realm *realm;
1173 for (entry = list_first(realms); entry; entry = list_next(entry)) {
1174 realm = (struct realm *)entry->data;
1175 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1176 debug(DBG_DBG, "found matching realm: %s", realm->name);
1183 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
1186 pthread_mutex_lock(&to->newrq_mutex);
1187 for (i = 0; i < MAX_REQUESTS; i++)
1188 if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
1190 pthread_mutex_unlock(&to->newrq_mutex);
1192 return i < MAX_REQUESTS;
1195 int attrvalidate(unsigned char *attrs, int length) {
1196 while (length > 1) {
1197 if (ATTRLEN(attrs) < 2) {
1198 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1201 length -= ATTRLEN(attrs);
1203 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1206 attrs += ATTRLEN(attrs);
1209 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1213 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1214 if (len < 16 || len > 128 || len % 16) {
1215 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1219 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1220 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1224 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1226 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1227 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1233 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1236 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1237 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1240 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1241 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1247 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1248 char *oldsecret, char *newsecret) {
1249 unsigned char *attr;
1251 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1252 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1253 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1259 /* returns a pointer to the resized attribute value */
1260 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1261 uint8_t *attrs, *attr, vallen;
1265 len = RADLEN(*buf) - 20;
1268 attr = attrget(attrs, len, type);
1272 vallen = ATTRVALLEN(attr);
1273 if (vallen == newvallen)
1276 len += newvallen - vallen;
1277 if (newvallen > vallen) {
1278 new = realloc(*buf, len);
1280 debug(DBG_ERR, "resizeattr: malloc failed");
1289 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1290 attr[1] = newvallen + 2;
1291 ((uint16_t *)*buf)[1] = htons(len + 20);
1295 int rewriteusername(struct request *rq, char *in) {
1296 size_t nmatch = 10, reslen = 0, start = 0;
1297 regmatch_t pmatch[10], *pfield;
1299 unsigned char *result;
1300 char *out = rq->from->conf->rewriteattrreplacement;
1302 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1303 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1307 rq->origusername = stringcopy(in, 0);
1308 if (!rq->origusername)
1311 for (i = start; out[i]; i++) {
1312 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1313 pfield = &pmatch[out[i + 1] - '0'];
1314 if (pfield->rm_so >= 0) {
1315 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1321 reslen += i - start;
1323 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1329 for (i = start; out[i]; i++) {
1330 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1331 pfield = &pmatch[out[i + 1] - '0'];
1332 if (pfield->rm_so >= 0) {
1333 memcpy(result + reslen, out + start, i - start);
1334 reslen += i - start;
1335 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1336 reslen += pfield->rm_eo - pfield->rm_so;
1343 memcpy(result + reslen, out + start, i - start);
1344 reslen += i - start;
1345 memcpy(in, result, reslen);
1350 void acclog(unsigned char *attrs, int length, char *host) {
1351 unsigned char *attr;
1354 attr = attrget(attrs, length, RAD_Attr_User_Name);
1356 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1359 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1360 username[ATTRVALLEN(attr)] = '\0';
1361 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1364 void respondaccounting(struct request *rq) {
1365 unsigned char *resp;
1369 debug(DBG_ERR, "respondstatusserver: malloc failed");
1372 memcpy(resp, rq->buf, 20);
1373 resp[0] = RAD_Accounting_Response;
1376 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1377 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1380 void respondstatusserver(struct request *rq) {
1381 unsigned char *resp;
1385 debug(DBG_ERR, "respondstatusserver: malloc failed");
1388 memcpy(resp, rq->buf, 20);
1389 resp[0] = RAD_Access_Accept;
1392 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1393 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1396 void respondreject(struct request *rq, char *message) {
1397 unsigned char *resp;
1400 if (message && *message)
1401 len += 2 + strlen(message);
1405 debug(DBG_ERR, "respondreject: malloc failed");
1408 memcpy(resp, rq->buf, 20);
1409 resp[0] = RAD_Access_Reject;
1410 *(uint16_t *)(resp + 2) = htons(len);
1411 if (message && *message) {
1412 resp[20] = RAD_Attr_Reply_Message;
1413 resp[21] = len - 20;
1414 memcpy(resp + 22, message, len - 22);
1416 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1419 struct server *realm2server(struct realm *realm) {
1420 struct list_node *entry;
1421 struct server *server, *best = NULL;
1423 for (entry = list_first(realm->srvconfs); entry; entry = list_next(entry)) {
1424 server = ((struct clsrvconf *)entry->data)->servers;
1425 if (!server->connectionok)
1427 if (!server->loststatsrv)
1433 if (server->loststatsrv < best->loststatsrv)
1439 void radsrv(struct request *rq) {
1440 uint8_t code, id, *auth, *attrs, *attr;
1442 struct server *to = NULL;
1444 unsigned char newauth[16];
1445 struct realm *realm = NULL;
1447 code = *(uint8_t *)rq->buf;
1448 id = *(uint8_t *)(rq->buf + 1);
1449 len = RADLEN(rq->buf);
1450 auth = (uint8_t *)(rq->buf + 4);
1452 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1454 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1455 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1461 attrs = rq->buf + 20;
1463 if (!attrvalidate(attrs, len)) {
1464 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1469 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1470 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
1471 debug(DBG_WARN, "radsrv: message authentication failed");
1476 if (code != RAD_Access_Request) {
1478 case RAD_Accounting_Request:
1479 acclog(attrs, len, rq->from->conf->host);
1480 respondaccounting(rq);
1482 case RAD_Status_Server:
1483 respondstatusserver(rq);
1490 /* code == RAD_Access_Request */
1491 attr = attrget(attrs, len, RAD_Attr_User_Name);
1493 debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1497 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1498 username[ATTRVALLEN(attr)] = '\0';
1500 if (rq->from->conf->rewriteattrregex) {
1501 if (!rewriteusername(rq, username)) {
1502 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1506 len = RADLEN(rq->buf) - 20;
1507 auth = (uint8_t *)(rq->buf + 4);
1508 attrs = rq->buf + 20;
1511 if (rq->origusername)
1512 debug(DBG_DBG, "Access Request with username: %s (originally %s)", username, rq->origusername);
1514 debug(DBG_DBG, "Access Request with username: %s", username);
1516 realm = id2realm(username, strlen(username));
1518 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1523 to = realm2server(realm);
1524 if (to && rqinqueue(to, rq->from, id)) {
1525 debug(DBG_INFO, "radsrv: already got request from host %s with id %d, ignoring", rq->from->conf->host, id);
1531 if (realm->message) {
1532 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, username);
1533 respondreject(rq, realm->message);
1539 if (!RAND_bytes(newauth, 16)) {
1540 debug(DBG_WARN, "radsrv: failed to generate random auth");
1546 printfchars(NULL, "auth", "%02x ", auth, 16);
1549 attr = attrget(attrs, len, RAD_Attr_User_Password);
1551 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1552 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1558 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1560 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1561 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1568 memcpy(rq->origauth, auth, 16);
1569 memcpy(auth, newauth, 16);
1573 int replyh(struct server *server, unsigned char *buf) {
1574 struct client *from;
1577 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
1578 struct sockaddr_storage fromsa;
1581 server->connectionok = 1;
1582 server->loststatsrv = 0;
1584 i = buf[1]; /* i is the id */
1587 case RAD_Access_Accept:
1588 debug(DBG_DBG, "got Access Accept with id %d", i);
1590 case RAD_Access_Reject:
1591 debug(DBG_DBG, "got Access Reject with id %d", i);
1593 case RAD_Access_Challenge:
1594 debug(DBG_DBG, "got Access Challenge with id %d", i);
1597 debug(DBG_INFO, "replyh: discarding, only accept access accept, access reject and access challenge messages");
1601 rq = server->requests + i;
1603 pthread_mutex_lock(&server->newrq_mutex);
1604 if (!rq->buf || !rq->tries) {
1605 pthread_mutex_unlock(&server->newrq_mutex);
1606 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
1611 pthread_mutex_unlock(&server->newrq_mutex);
1612 debug(DBG_INFO, "replyh: already received, ignoring reply");
1616 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
1617 pthread_mutex_unlock(&server->newrq_mutex);
1618 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
1623 len = RADLEN(buf) - 20;
1626 if (!attrvalidate(attrs, len)) {
1627 pthread_mutex_unlock(&server->newrq_mutex);
1628 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
1632 /* Message Authenticator */
1633 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1635 if (ATTRVALLEN(messageauth) != 16) {
1636 pthread_mutex_unlock(&server->newrq_mutex);
1637 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
1640 memcpy(tmp, buf + 4, 16);
1641 memcpy(buf + 4, rq->buf + 4, 16);
1642 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
1643 pthread_mutex_unlock(&server->newrq_mutex);
1644 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
1647 memcpy(buf + 4, tmp, 16);
1648 debug(DBG_DBG, "replyh: message auth ok");
1651 if (*rq->buf == RAD_Status_Server) {
1653 pthread_mutex_unlock(&server->newrq_mutex);
1654 debug(DBG_INFO, "replyh: got status server response from %s", server->conf->host);
1659 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1660 if (ATTRVALLEN(attr) <= 4)
1663 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
1666 sublen = ATTRVALLEN(attr) - 4;
1667 subattrs = ATTRVAL(attr) + 4;
1668 if (!attrvalidate(subattrs, sublen) ||
1669 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1670 rq, server->conf->secret, from->conf->secret) ||
1671 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1672 rq, server->conf->secret, from->conf->secret))
1676 pthread_mutex_unlock(&server->newrq_mutex);
1677 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1681 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject) {
1682 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
1683 /* we know the attribute exists */
1684 memcpy(tmp, ATTRVAL(attr), ATTRVALLEN(attr));
1685 tmp[ATTRVALLEN(attr)] = '\0';
1687 case RAD_Access_Accept:
1688 if (rq->origusername)
1689 debug(DBG_INFO, "Access Accept for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1691 debug(DBG_INFO, "Access Accept for %s from %s", tmp, server->conf->host);
1693 case RAD_Access_Reject:
1694 if (rq->origusername)
1695 debug(DBG_INFO, "Access Reject for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1697 debug(DBG_INFO, "Access Reject for %s from %s", tmp, server->conf->host);
1702 buf[1] = (char)rq->origid;
1703 memcpy(buf + 4, rq->origauth, 16);
1705 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1708 if (rq->origusername) {
1709 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
1711 pthread_mutex_unlock(&server->newrq_mutex);
1712 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1715 memcpy(username, rq->origusername, strlen(rq->origusername));
1716 len = RADLEN(buf) - 20;
1719 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1723 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
1724 pthread_mutex_unlock(&server->newrq_mutex);
1725 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
1728 debug(DBG_DBG, "replyh: computed messageauthattr");
1731 if (from->conf->type == 'U')
1732 fromsa = rq->fromsa;
1733 /* once we set received = 1, rq may be reused */
1735 pthread_mutex_unlock(&server->newrq_mutex);
1737 debug(DBG_DBG, "replyh: giving packet back to where it came from");
1738 sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
1742 void *clientrd(void *arg) {
1743 struct server *server = (struct server *)arg;
1745 struct timeval lastconnecttry;
1748 /* yes, lastconnecttry is really necessary */
1749 lastconnecttry = server->lastconnecttry;
1750 buf = (server->conf->type == 'U' ? radudpget(server->sock, NULL, &server, NULL) : radtlsget(server->ssl));
1751 if (!buf && server->conf->type == 'T') {
1752 tlsconnect(server, &lastconnecttry, "clientrd");
1756 if (!replyh(server, buf))
1761 void *clientwr(void *arg) {
1762 struct server *server = (struct server *)arg;
1764 pthread_t clientrdth;
1767 struct timeval now, lastsend;
1768 struct timespec timeout;
1769 struct request statsrvrq;
1770 unsigned char statsrvbuf[38];
1772 memset(&timeout, 0, sizeof(struct timespec));
1774 if (server->conf->statusserver) {
1775 memset(&statsrvrq, 0, sizeof(struct request));
1776 memset(statsrvbuf, 0, sizeof(statsrvbuf));
1777 statsrvbuf[0] = RAD_Status_Server;
1779 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
1780 statsrvbuf[21] = 18;
1781 gettimeofday(&lastsend, NULL);
1784 if (server->conf->type == 'U') {
1785 if ((server->sock = connecttoserver(server->conf->addrinfo)) < 0)
1786 debugx(1, DBG_ERR, "clientwr: connecttoserver failed");
1788 tlsconnect(server, NULL, "new client");
1790 server->connectionok = 1;
1792 if (pthread_create(&clientrdth, NULL, clientrd, (void *)server))
1793 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
1796 pthread_mutex_lock(&server->newrq_mutex);
1797 if (!server->newrq) {
1798 gettimeofday(&now, NULL);
1799 if (server->conf->statusserver) {
1800 /* random 0-7 seconds */
1801 RAND_bytes(&rnd, 1);
1803 if (!timeout.tv_sec || timeout.tv_sec - now.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
1804 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
1806 if (timeout.tv_sec) {
1807 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1808 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1811 debug(DBG_DBG, "clientwr: waiting for new request");
1812 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1815 if (server->newrq) {
1816 debug(DBG_DBG, "clientwr: got new request");
1819 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1820 pthread_mutex_unlock(&server->newrq_mutex);
1822 for (i = 0; i < MAX_REQUESTS; i++) {
1823 pthread_mutex_lock(&server->newrq_mutex);
1824 while (i < MAX_REQUESTS && !server->requests[i].buf)
1826 if (i == MAX_REQUESTS) {
1827 pthread_mutex_unlock(&server->newrq_mutex);
1830 rq = server->requests + i;
1833 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
1835 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
1837 /* setting this to NULL means that it can be reused */
1840 pthread_mutex_unlock(&server->newrq_mutex);
1844 gettimeofday(&now, NULL);
1845 if (now.tv_sec < rq->expiry.tv_sec) {
1846 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1847 timeout.tv_sec = rq->expiry.tv_sec;
1848 pthread_mutex_unlock(&server->newrq_mutex);
1852 if (rq->tries == (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
1853 ? 1 : REQUEST_RETRIES)) {
1854 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1855 if (*rq->buf == RAD_Status_Server) {
1856 debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->conf->host);
1857 if (server->loststatsrv < 255)
1858 server->loststatsrv++;
1861 /* setting this to NULL means that it can be reused */
1863 pthread_mutex_unlock(&server->newrq_mutex);
1866 pthread_mutex_unlock(&server->newrq_mutex);
1868 rq->expiry.tv_sec = now.tv_sec +
1869 (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
1870 ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
1871 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1872 timeout.tv_sec = rq->expiry.tv_sec;
1874 clientradput(server, server->requests[i].buf);
1875 gettimeofday(&lastsend, NULL);
1877 if (server->conf->statusserver) {
1878 gettimeofday(&now, NULL);
1879 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
1880 if (!RAND_bytes(statsrvbuf + 4, 16)) {
1881 debug(DBG_WARN, "clientwr: failed to generate random auth");
1884 statsrvrq.buf = malloc(sizeof(statsrvbuf));
1885 if (!statsrvrq.buf) {
1886 debug(DBG_ERR, "clientwr: malloc failed");
1889 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
1890 debug(DBG_DBG, "clientwr: sending status server to %s", server->conf->host);
1891 lastsend.tv_sec = now.tv_sec;
1892 sendrq(server, &statsrvrq);
1898 void *udpserverwr(void *arg) {
1899 struct replyq *replyq = udp_server_replyq;
1900 struct reply *reply;
1903 pthread_mutex_lock(&replyq->mutex);
1904 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
1905 debug(DBG_DBG, "udp server writer, waiting for signal");
1906 pthread_cond_wait(&replyq->cond, &replyq->mutex);
1907 debug(DBG_DBG, "udp server writer, got signal");
1909 pthread_mutex_unlock(&replyq->mutex);
1911 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
1912 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
1913 debug(DBG_WARN, "sendudp: send failed");
1919 void *udpserverrd(void *arg) {
1921 pthread_t udpserverwrth;
1923 if ((udp_server_sock = bindtoaddr(udp_server_listen->addrinfo)) < 0)
1924 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
1926 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
1927 udp_server_listen->host ? udp_server_listen->host : "*", udp_server_listen->port);
1929 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
1930 debugx(1, DBG_ERR, "pthread_create failed");
1933 memset(&rq, 0, sizeof(struct request));
1934 rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
1939 void *udpaccserverrd(void *arg) {
1942 if ((udp_accserver_sock = bindtoaddr(udp_accserver_listen->addrinfo)) < 0)
1943 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
1945 debug(DBG_WARN, "udpaccserverrd: listening for UDP on %s:%s",
1946 udp_accserver_listen->host ? udp_accserver_listen->host : "*", udp_accserver_listen->port);
1949 memset(&rq, 0, sizeof(struct request));
1950 rq.buf = radudpget(udp_accserver_sock, &rq.from, NULL, &rq.fromsa);
1951 if (*(uint8_t *)rq.buf == RAD_Accounting_Request) {
1955 debug(DBG_INFO, "udpaccserverrd: got something other than accounting-request, ignoring");
1960 void *tlsserverwr(void *arg) {
1962 unsigned long error;
1963 struct client *client = (struct client *)arg;
1964 struct replyq *replyq;
1965 struct reply *reply;
1967 debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
1968 replyq = client->replyq;
1970 pthread_mutex_lock(&replyq->mutex);
1971 while (!list_first(replyq->replies)) {
1973 debug(DBG_DBG, "tls server writer, waiting for signal");
1974 pthread_cond_wait(&replyq->cond, &replyq->mutex);
1975 debug(DBG_DBG, "tls server writer, got signal");
1978 /* ssl might have changed while waiting */
1979 pthread_mutex_unlock(&replyq->mutex);
1980 debug(DBG_DBG, "tlsserverwr: exiting as requested");
1984 reply = (struct reply *)list_shift(replyq->replies);
1985 pthread_mutex_unlock(&replyq->mutex);
1986 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
1988 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
1989 cnt, RADLEN(reply->buf));
1991 while ((error = ERR_get_error()))
1992 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
1998 void *tlsserverrd(void *arg) {
2000 unsigned long error;
2002 struct client *client = (struct client *)arg;
2003 pthread_t tlsserverwrth;
2006 debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2009 if (SSL_accept(ssl) <= 0) {
2010 while ((error = ERR_get_error()))
2011 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2012 debug(DBG_ERR, "SSL_accept failed");
2015 if (tlsverifycert(client->ssl, client->conf)) {
2016 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2017 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2021 memset(&rq, 0, sizeof(struct request));
2022 rq.buf = radtlsget(client->ssl);
2025 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2029 debug(DBG_ERR, "tlsserverrd: connection lost");
2030 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2032 pthread_mutex_lock(&client->replyq->mutex);
2033 pthread_cond_signal(&client->replyq->cond);
2034 pthread_mutex_unlock(&client->replyq->mutex);
2035 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2036 pthread_join(tlsserverwrth, NULL);
2040 s = SSL_get_fd(ssl);
2042 shutdown(s, SHUT_RDWR);
2044 debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->conf->host);
2045 removeclient(client);
2050 pthread_t tlsserverth;
2052 struct sockaddr_storage from;
2053 size_t fromlen = sizeof(from);
2054 struct clsrvconf *conf;
2055 struct client *client;
2057 if ((s = bindtoaddr(tcp_server_listen->addrinfo)) < 0)
2058 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
2061 debug(DBG_WARN, "listening for incoming TCP on %s:%s",
2062 tcp_server_listen->host ? tcp_server_listen->host : "*", tcp_server_listen->port);
2065 snew = accept(s, (struct sockaddr *)&from, &fromlen);
2067 debug(DBG_WARN, "accept failed");
2070 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2072 conf = find_conf('T', (struct sockaddr *)&from, clconfs, NULL);
2074 debug(DBG_WARN, "ignoring request, not a known TLS client");
2075 shutdown(snew, SHUT_RDWR);
2080 client = addclient(conf);
2083 debug(DBG_WARN, "Failed to create new client instance");
2084 shutdown(snew, SHUT_RDWR);
2088 client->ssl = SSL_new(client->conf->ssl_ctx);
2089 SSL_set_fd(client->ssl, snew);
2090 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
2091 debug(DBG_ERR, "tlslistener: pthread_create failed");
2092 SSL_free(client->ssl);
2093 removeclient(client);
2094 shutdown(snew, SHUT_RDWR);
2098 pthread_detach(tlsserverth);
2103 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
2107 unsigned long error;
2109 if (!certfile || !certkeyfile)
2110 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2112 if (!cacertfile && !cacertpath)
2113 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2116 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2117 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2118 for (i = 0; i < CRYPTO_num_locks(); i++) {
2119 ssl_lock_count[i] = 0;
2120 pthread_mutex_init(&ssl_locks[i], NULL);
2122 CRYPTO_set_id_callback(ssl_thread_id);
2123 CRYPTO_set_locking_callback(ssl_locking_callback);
2125 SSL_load_error_strings();
2128 while (!RAND_status()) {
2129 time_t t = time(NULL);
2130 pid_t pid = getpid();
2131 RAND_seed((unsigned char *)&t, sizeof(time_t));
2132 RAND_seed((unsigned char *)&pid, sizeof(pid));
2135 ctx = SSL_CTX_new(TLSv1_method());
2137 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2138 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2140 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2141 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2142 !SSL_CTX_check_private_key(ctx) ||
2143 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2144 while ((error = ERR_get_error()))
2145 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2146 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2149 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2150 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2152 new = malloc(sizeof(struct tls));
2153 if (!new || !list_push(tlsconfs, new))
2154 debugx(1, DBG_ERR, "malloc failed");
2156 memset(new, 0, sizeof(struct tls));
2157 new->name = stringcopy(value, 0);
2159 debugx(1, DBG_ERR, "malloc failed");
2162 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2166 struct list_node *entry;
2169 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2170 t = (struct tls *)entry->data;
2174 SSL_CTX_free(t->ctx);
2176 list_destroy(tlsconfs);
2180 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2181 struct list_node *entry;
2182 struct tls *t, *t1 = NULL, *t2 = NULL;
2184 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2185 t = (struct tls *)entry->data;
2186 if (!strcasecmp(t->name, alt1)) {
2190 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2201 void addrealm(char *value, char **servers, char *message) {
2203 struct realm *realm;
2204 char *s, *regex = NULL;
2205 struct list_node *entry;
2206 struct clsrvconf *conf;
2208 if (*value == '/') {
2209 /* regexp, remove optional trailing / if present */
2210 if (value[strlen(value) - 1] == '/')
2211 value[strlen(value) - 1] = '\0';
2213 /* not a regexp, let us make it one */
2214 if (*value == '*' && !value[1])
2215 regex = stringcopy(".*", 0);
2217 for (n = 0, s = value; *s;)
2220 regex = malloc(strlen(value) + n + 3);
2223 for (n = 1, s = value; *s; s++) {
2233 debugx(1, DBG_ERR, "malloc failed");
2234 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2237 realm = malloc(sizeof(struct realm));
2239 debugx(1, DBG_ERR, "malloc failed");
2241 memset(realm, 0, sizeof(struct realm));
2242 realm->name = stringcopy(value, 0);
2244 debugx(1, DBG_ERR, "malloc failed");
2245 if (message && strlen(message) > 253)
2246 debugx(1, DBG_ERR, "ReplyMessage can be at most 253 bytes");
2247 realm->message = message;
2249 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB))
2250 debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2254 if (servers && *servers) {
2255 realm->srvconfs = list_create();
2256 if (!realm->srvconfs)
2257 debugx(1, DBG_ERR, "malloc failed");
2258 for (n = 0; servers[n]; n++) {
2259 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2260 conf = (struct clsrvconf *)entry->data;
2261 if (!strcasecmp(servers[n], conf->name))
2265 debugx(1, DBG_ERR, "addrealm failed, no server %s", servers[n]);
2266 if (!list_push(realm->srvconfs, conf))
2267 debugx(1, DBG_ERR, "malloc failed");
2268 debug(DBG_DBG, "addrealm: added server %s for realm %s", conf->name, value);
2271 realm->srvconfs = NULL;
2273 if (!list_push(realms, realm))
2274 debugx(1, DBG_ERR, "malloc failed");
2275 debug(DBG_DBG, "addrealm: added realm %s", value);
2278 char *parsehostport(char *s, struct clsrvconf *conf) {
2283 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
2287 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
2289 debugx(1, DBG_ERR, "no ] matching initial [");
2293 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
2296 debugx(1, DBG_ERR, "missing host/address");
2298 conf->host = stringcopy(field, p - field);
2301 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
2302 debugx(1, DBG_ERR, "unexpected character after ]");
2305 /* port number or service name is specified */;
2307 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
2309 debugx(1, DBG_ERR, "syntax error, : but no following port");
2310 conf->port = stringcopy(field, p - field);
2312 conf->port = stringcopy(conf->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT, 0);
2316 FILE *openconfigfile(const char *filename) {
2318 char pathname[100], *base = NULL;
2320 f = fopen(filename, "r");
2322 debug(DBG_DBG, "reading config file %s", filename);
2326 if (strlen(filename) + 1 <= sizeof(pathname)) {
2327 /* basename() might modify the string */
2328 strcpy(pathname, filename);
2329 base = basename(pathname);
2330 f = fopen(base, "r");
2334 debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
2336 debug(DBG_DBG, "reading config file %s", base);
2340 struct clsrvconf *server_create(char type, char *lconf) {
2341 struct clsrvconf *conf;
2343 conf = malloc(sizeof(struct clsrvconf));
2345 debugx(1, DBG_ERR, "malloc failed");
2346 memset(conf, 0, sizeof(struct clsrvconf));
2349 parsehostport(lconf, conf);
2350 if (!strcmp(conf->host, "*")) {
2355 conf->port = stringcopy(type == 'T' ? DEFAULT_TLS_PORT : DEFAULT_UDP_PORT, 0);
2356 if (!resolvepeer(conf, AI_PASSIVE))
2357 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2361 /* returns NULL on error, where to continue parsing if token and ok. E.g. "" will return token with empty string */
2362 char *strtokenquote(char *s, char **token, char *del, char *quote, char *comment) {
2363 char *t = s, *q, *r;
2365 if (!t || !token || !del)
2367 while (*t && strchr(del, *t))
2369 if (!*t || (comment && strchr(comment, *t))) {
2371 return t + 1; /* needs to be non-NULL, but value doesn't matter */
2373 if (quote && (q = strchr(quote, *t))) {
2376 while (*t && *t != *q)
2378 if (!*t || (t[1] && !strchr(del, t[1])))
2386 while (*t && !strchr(del, *t))
2392 /* Parses config with following syntax:
2395 * option-name = value
2397 * option-name value {
2398 * option-name [=] value
2402 void getgeneralconfig(FILE *f, char *block, ...) {
2405 /* initialise lots of stuff to avoid stupid compiler warnings */
2406 char *tokens[3], *s, *opt = NULL, *val = NULL, *word, *optval, **str = NULL, ***mstr = NULL;
2407 int type = 0, tcount, conftype = 0, n;
2408 void (*cbk)(FILE *, char *, char *, char *) = NULL;
2410 while (fgets(line, 1024, f)) {
2412 for (tcount = 0; tcount < 3; tcount++) {
2413 s = strtokenquote(s, &tokens[tcount], " \t\r\n", "\"'", tcount ? NULL : "#");
2415 debugx(1, DBG_ERR, "Syntax error in line starting with: %s", line);
2416 if (!tokens[tcount])
2419 if (!tcount || **tokens == '#')
2422 if (**tokens == '}') {
2425 debugx(1, DBG_ERR, "configuration error, found } with no matching {");
2432 conftype = CONF_STR;
2435 if (tokens[1][0] == '=' && tokens[1][1] == '\0') {
2438 conftype = CONF_STR;
2441 if (tokens[2][0] == '{' && tokens[2][1] == '\0') {
2444 conftype = CONF_CBK;
2450 debugx(1, DBG_ERR, "configuration error in block %s, line starting with %s", block, tokens[0]);
2451 debugx(1, DBG_ERR, "configuration error, syntax error in line starting with %s", tokens[0]);
2455 debugx(1, DBG_ERR, "configuration error, option %s needs a non-empty value", opt);
2457 va_start(ap, block);
2458 while ((word = va_arg(ap, char *))) {
2459 type = va_arg(ap, int);
2462 str = va_arg(ap, char **);
2464 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2467 mstr = va_arg(ap, char ***);
2469 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2472 cbk = va_arg(ap, void (*)(FILE *, char *, char *, char *));
2475 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2477 if (!strcasecmp(opt, word))
2484 debugx(1, DBG_ERR, "configuration error in block %s, unknown option %s", block, opt);
2485 debugx(1, DBG_ERR, "configuration error, unknown option %s", opt);
2488 if (((type == CONF_STR || type == CONF_MSTR) && conftype != CONF_STR) ||
2489 (type == CONF_CBK && conftype != CONF_CBK)) {
2491 debugx(1, DBG_ERR, "configuration error in block %s, wrong syntax for option %s", block, opt);
2492 debugx(1, DBG_ERR, "configuration error, wrong syntax for option %s", opt);
2498 debug(DBG_DBG, "getgeneralconfig: block %s: %s = %s", block, opt, val);
2500 debug(DBG_DBG, "getgeneralconfig: %s = %s", opt, val);
2501 *str = stringcopy(val, 0);
2503 debugx(1, DBG_ERR, "malloc failed");
2507 debug(DBG_DBG, "getgeneralconfig: block %s: %s = %s", block, opt, val);
2509 debug(DBG_DBG, "getgeneralconfig: %s = %s", opt, val);
2511 for (n = 0; (*mstr)[n]; n++);
2514 *mstr = realloc(*mstr, sizeof(char *) * (n + 2));
2516 debugx(1, DBG_ERR, "malloc failed");
2517 (*mstr)[n] = stringcopy(val, 0);
2518 (*mstr)[n + 1] = NULL;
2521 optval = malloc(strlen(opt) + strlen(val) + 2);
2523 debugx(1, DBG_ERR, "malloc failed");
2524 sprintf(optval, "%s %s", opt, val);
2525 cbk(f, optval, opt, val);
2529 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2534 int addmatchcertattr(struct clsrvconf *conf, char *matchcertattr) {
2537 v = matchcertattr + 20;
2538 if (strncasecmp(matchcertattr, "SubjectAltName:URI:/", 20) || !*v)
2540 /* regexp, remove optional trailing / if present */
2541 if (v[strlen(v) - 1] == '/')
2542 v[strlen(v) - 1] = '\0';
2546 conf->certuriregex = malloc(sizeof(regex_t));
2547 if (!conf->certuriregex) {
2548 debug(DBG_ERR, "malloc failed");
2551 if (regcomp(conf->certuriregex, v, REG_ICASE | REG_NOSUB)) {
2552 free(conf->certuriregex);
2553 conf->certuriregex = NULL;
2554 debug(DBG_ERR, "failed to compile regular expression %s", v);
2560 int addrewriteattr(struct clsrvconf *conf, char *rewriteattr) {
2563 v = rewriteattr + 11;
2564 if (strncasecmp(rewriteattr, "User-Name:/", 11) || !*v)
2566 /* regexp, remove optional trailing / if present */
2567 if (v[strlen(v) - 1] == '/')
2568 v[strlen(v) - 1] = '\0';
2576 conf->rewriteattrregex = malloc(sizeof(regex_t));
2577 if (!conf->rewriteattrregex) {
2578 debug(DBG_ERR, "malloc failed");
2582 conf->rewriteattrreplacement = stringcopy(w, 0);
2583 if (!conf->rewriteattrreplacement) {
2584 free(conf->rewriteattrregex);
2585 conf->rewriteattrregex = NULL;
2589 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
2590 free(conf->rewriteattrregex);
2591 conf->rewriteattrregex = NULL;
2592 free(conf->rewriteattrreplacement);
2593 conf->rewriteattrreplacement = NULL;
2594 debug(DBG_ERR, "failed to compile regular expression %s", v);
2601 void confclient_cb(FILE *f, char *block, char *opt, char *val) {
2602 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *rewriteattr = NULL;
2603 struct clsrvconf *conf;
2605 debug(DBG_DBG, "confclient_cb called for %s", block);
2607 conf = malloc(sizeof(struct clsrvconf));
2608 if (!conf || !list_push(clconfs, conf))
2609 debugx(1, DBG_ERR, "malloc failed");
2610 memset(conf, 0, sizeof(struct clsrvconf));
2612 getgeneralconfig(f, block,
2613 "type", CONF_STR, &type,
2614 "host", CONF_STR, &conf->host,
2615 "secret", CONF_STR, &conf->secret,
2616 "tls", CONF_STR, &tls,
2617 "matchcertificateattribute", CONF_STR, &matchcertattr,
2618 "rewriteattribute", CONF_STR, &rewriteattr,
2622 /* leave conf->name to be NULL for clients */
2624 conf->host = stringcopy(val, 0);
2626 if (type && !strcasecmp(type, "udp")) {
2629 } else if (type && !strcasecmp(type, "tls")) {
2630 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultclient", "default");
2632 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2633 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2634 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2638 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2643 free(matchcertattr);
2646 if (!addrewriteattr(conf, rewriteattr))
2647 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2651 if (!resolvepeer(conf, 0))
2652 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2654 if (!conf->secret) {
2655 if (conf->type == 'U')
2656 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2657 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2661 void confserver_cb(FILE *f, char *block, char *opt, char *val) {
2662 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *statusserver = NULL;
2663 struct clsrvconf *conf;
2665 debug(DBG_DBG, "confserver_cb called for %s", block);
2667 conf = malloc(sizeof(struct clsrvconf));
2668 if (!conf || !list_push(srvconfs, conf))
2669 debugx(1, DBG_ERR, "malloc failed");
2670 memset(conf, 0, sizeof(struct clsrvconf));
2672 getgeneralconfig(f, block,
2673 "type", CONF_STR, &type,
2674 "host", CONF_STR, &conf->host,
2675 "port", CONF_STR, &conf->port,
2676 "secret", CONF_STR, &conf->secret,
2677 "tls", CONF_STR, &tls,
2678 "matchcertificateattribute", CONF_STR, &matchcertattr,
2679 "StatusServer", CONF_STR, &statusserver,
2683 conf->name = stringcopy(val, 0);
2685 conf->host = stringcopy(val, 0);
2687 if (type && !strcasecmp(type, "udp")) {
2691 conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
2692 } else if (type && !strcasecmp(type, "tls")) {
2693 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultserver", "default");
2695 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2696 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2697 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2699 conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
2703 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2708 free(matchcertattr);
2710 if (!resolvepeer(conf, 0))
2711 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2713 if (!conf->secret) {
2714 if (conf->type == 'U')
2715 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2716 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2720 if (!strcasecmp(statusserver, "on"))
2721 conf->statusserver = 1;
2722 else if (strcasecmp(statusserver, "off"))
2723 debugx(1, DBG_ERR, "error in block %s, StatusServer is %s, must be on or off", block, statusserver);
2728 void confrealm_cb(FILE *f, char *block, char *opt, char *val) {
2729 char **servers = NULL, *msg = NULL;
2731 debug(DBG_DBG, "confrealm_cb called for %s", block);
2733 getgeneralconfig(f, block,
2734 "server", CONF_MSTR, &servers,
2735 "ReplyMessage", CONF_STR, &msg,
2739 addrealm(val, servers, msg);
2743 void conftls_cb(FILE *f, char *block, char *opt, char *val) {
2744 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
2746 debug(DBG_DBG, "conftls_cb called for %s", block);
2748 getgeneralconfig(f, block,
2749 "CACertificateFile", CONF_STR, &cacertfile,
2750 "CACertificatePath", CONF_STR, &cacertpath,
2751 "CertificateFile", CONF_STR, &certfile,
2752 "CertificateKeyFile", CONF_STR, &certkeyfile,
2753 "CertificateKeyPassword", CONF_STR, &certkeypwd,
2757 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
2765 void getmainconfig(const char *configfile) {
2767 char *loglevel = NULL;
2769 f = openconfigfile(configfile);
2770 memset(&options, 0, sizeof(options));
2772 clconfs = list_create();
2774 debugx(1, DBG_ERR, "malloc failed");
2776 srvconfs = list_create();
2778 debugx(1, DBG_ERR, "malloc failed");
2780 realms = list_create();
2782 debugx(1, DBG_ERR, "malloc failed");
2784 tlsconfs = list_create();
2786 debugx(1, DBG_ERR, "malloc failed");
2788 getgeneralconfig(f, NULL,
2789 "ListenUDP", CONF_STR, &options.listenudp,
2790 "ListenTCP", CONF_STR, &options.listentcp,
2791 "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
2792 "LogLevel", CONF_STR, &loglevel,
2793 "LogDestination", CONF_STR, &options.logdestination,
2794 "Client", CONF_CBK, confclient_cb,
2795 "Server", CONF_CBK, confserver_cb,
2796 "Realm", CONF_CBK, confrealm_cb,
2797 "TLS", CONF_CBK, conftls_cb,
2804 if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
2805 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
2806 options.loglevel = *loglevel - '0';
2811 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *loglevel, char **configfile) {
2814 while ((c = getopt(argc, argv, "c:d:fv")) != -1) {
2817 *configfile = optarg;
2820 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
2821 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
2822 *loglevel = *optarg - '0';
2828 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
2833 if (!(argc - optind))
2837 debug(DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -v ]", argv[0]);
2841 int main(int argc, char **argv) {
2842 pthread_t udpserverth, udpaccserverth;
2843 struct list_node *entry;
2844 uint8_t foreground = 0, loglevel = 0;
2845 char *configfile = NULL;
2847 debug_init("radsecproxy");
2848 debug_set_level(DEBUG_LEVEL);
2849 getargs(argc, argv, &foreground, &loglevel, &configfile);
2851 debug_set_level(loglevel);
2852 getmainconfig(configfile ? configfile : CONFIG_MAIN);
2854 options.loglevel = loglevel;
2855 else if (options.loglevel)
2856 debug_set_level(options.loglevel);
2858 options.logdestination = NULL;
2860 if (!options.logdestination)
2861 options.logdestination = "x-syslog:///";
2862 debug_set_destination(options.logdestination);
2865 if (!list_first(clconfs))
2866 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
2867 if (!list_first(srvconfs))
2868 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
2869 if (!list_first(realms))
2870 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
2872 if (!foreground && (daemon(0, 0) < 0))
2873 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
2875 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
2877 if (client_udp_count) {
2878 udp_server_listen = server_create('U', options.listenudp);
2879 udp_server_replyq = newreplyq();
2880 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
2881 debugx(1, DBG_ERR, "pthread_create failed");
2882 if (options.listenaccudp) {
2883 udp_accserver_listen = server_create('U', options.listenaccudp);
2884 if (pthread_create(&udpaccserverth, NULL, udpaccserverrd, NULL))
2885 debugx(1, DBG_ERR, "pthread_create failed");
2889 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2890 addserver((struct clsrvconf *)entry->data);
2891 if (pthread_create(&((struct clsrvconf *)entry->data)->servers->clientth, NULL, clientwr,
2892 (void *)((struct clsrvconf *)entry->data)->servers))
2893 debugx(1, DBG_ERR, "pthread_create failed");
2896 if (client_tls_count) {
2897 tcp_server_listen = server_create('T', options.listentcp);
2898 return tlslistener();
2901 /* just hang around doing nothing, anything to do here? */