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 int udp_client4_sock = -1;
68 static int udp_client6_sock = -1;
69 static pthread_mutex_t *ssl_locks;
70 static long *ssl_lock_count;
74 /* callbacks for making OpenSSL thread safe */
75 unsigned long ssl_thread_id() {
76 return (unsigned long)pthread_self();
79 void ssl_locking_callback(int mode, int type, const char *file, int line) {
80 if (mode & CRYPTO_LOCK) {
81 pthread_mutex_lock(&ssl_locks[type]);
82 ssl_lock_count[type]++;
84 pthread_mutex_unlock(&ssl_locks[type]);
87 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
88 int pwdlen = strlen(userdata);
89 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
91 memcpy(buf, userdata, pwdlen);
95 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
100 err_cert = X509_STORE_CTX_get_current_cert(ctx);
101 err = X509_STORE_CTX_get_error(ctx);
102 depth = X509_STORE_CTX_get_error_depth(ctx);
104 if (depth > MAX_CERT_DEPTH) {
106 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
107 X509_STORE_CTX_set_error(ctx, err);
111 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
112 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
115 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
116 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
117 debug(DBG_WARN, "\tIssuer=%s", buf);
119 case X509_V_ERR_CERT_NOT_YET_VALID:
120 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
121 debug(DBG_WARN, "\tCertificate not yet valid");
123 case X509_V_ERR_CERT_HAS_EXPIRED:
124 debug(DBG_WARN, "Certificate has expired");
126 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
127 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
132 printf("certificate verify returns %d\n", ok);
137 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
138 struct addrinfo hints, *addrinfo;
142 slash = conf->host ? strchr(conf->host, '/') : NULL;
146 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
150 if (*s < '0' || *s > '9') {
151 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
154 plen = atoi(slash + 1);
155 if (plen < 0 || plen > 128) {
156 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
161 memset(&hints, 0, sizeof(hints));
162 hints.ai_socktype = (conf->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
163 hints.ai_family = AF_UNSPEC;
164 hints.ai_flags = ai_flags;
166 hints.ai_flags |= AI_NUMERICHOST;
167 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
168 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host, conf->port);
174 switch (addrinfo->ai_family) {
177 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
178 freeaddrinfo(addrinfo);
185 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
186 freeaddrinfo(addrinfo);
189 conf->prefixlen = plen;
191 conf->prefixlen = 255;
194 freeaddrinfo(conf->addrinfo);
195 conf->addrinfo = addrinfo;
199 int connecttoserver(struct addrinfo *addrinfo) {
201 struct addrinfo *res;
204 for (res = addrinfo; res; res = res->ai_next) {
205 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
207 debug(DBG_WARN, "connecttoserver: socket failed");
210 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
212 debug(DBG_WARN, "connecttoserver: connect failed");
219 int bindtoaddr(struct addrinfo *addrinfo) {
221 struct addrinfo *res;
223 for (res = addrinfo; res; res = res->ai_next) {
224 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
226 debug(DBG_WARN, "bindtoaddr: socket failed");
229 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
230 if (!bind(s, res->ai_addr, res->ai_addrlen))
232 debug(DBG_WARN, "bindtoaddr: bind failed");
238 /* returns 1 if the len first bits are equal, else 0 */
239 int prefixmatch(void *a1, void *a2, uint8_t len) {
240 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
242 if (l && memcmp(a1, a2, l))
247 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
250 /* returns the config with matching address, or NULL */
251 /* if conf argument is not NULL, we only check that one */
252 struct clsrvconf *find_conf(char type, struct sockaddr *addr, struct list *confs, struct clsrvconf *conf) {
253 struct sockaddr_in6 *sa6 = NULL;
254 struct in_addr *a4 = NULL;
255 struct addrinfo *res;
256 struct list_node *entry;
258 if (addr->sa_family == AF_INET6) {
259 sa6 = (struct sockaddr_in6 *)addr;
260 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
261 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
265 a4 = &((struct sockaddr_in *)addr)->sin_addr;
268 if (conf->type == type) {
269 if (conf->prefixlen == 255) {
270 for (res = conf->addrinfo; res; res = res->ai_next)
271 if ((a4 && res->ai_family == AF_INET &&
272 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
273 (sa6 && res->ai_family == AF_INET6 &&
274 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
277 res = conf->addrinfo;
279 ((a4 && res->ai_family == AF_INET &&
280 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
281 (sa6 && res->ai_family == AF_INET6 &&
282 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
289 for (entry = list_first(confs); entry; entry = list_next(entry)) {
290 conf = (struct clsrvconf *)entry->data;
291 if (conf->type == type) {
292 if (conf->prefixlen == 255) {
293 for (res = conf->addrinfo; res; res = res->ai_next)
294 if ((a4 && res->ai_family == AF_INET &&
295 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
296 (sa6 && res->ai_family == AF_INET6 &&
297 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
300 res = conf->addrinfo;
302 ((a4 && res->ai_family == AF_INET &&
303 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
304 (sa6 && res->ai_family == AF_INET6 &&
305 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
313 struct replyq *newreplyq() {
314 struct replyq *replyq;
316 replyq = malloc(sizeof(struct replyq));
318 debugx(1, DBG_ERR, "malloc failed");
319 replyq->replies = list_create();
320 if (!replyq->replies)
321 debugx(1, DBG_ERR, "malloc failed");
322 pthread_mutex_init(&replyq->mutex, NULL);
323 pthread_cond_init(&replyq->cond, NULL);
327 struct client *addclient(struct clsrvconf *conf) {
328 struct client *new = malloc(sizeof(struct client));
331 debug(DBG_ERR, "malloc failed");
334 if (!conf->clients) {
335 conf->clients = list_create();
336 if (!conf->clients) {
337 debug(DBG_ERR, "malloc failed");
342 memset(new, 0, sizeof(struct client));
344 new->replyq = conf->type == 'T' ? newreplyq() : udp_server_replyq;
346 list_push(conf->clients, new);
350 void removeclient(struct client *client) {
351 if (!client || !client->conf->clients)
354 list_removedata(client->conf->clients, client);
358 void addserver(struct clsrvconf *conf) {
362 debugx(1, DBG_ERR, "addserver: currently works with just one server per conf");
364 conf->servers = malloc(sizeof(struct server));
366 debugx(1, DBG_ERR, "malloc failed");
367 memset(conf->servers, 0, sizeof(struct server));
368 conf->servers->conf = conf;
370 if (conf->type == 'U') {
371 switch (conf->addrinfo->ai_family) {
373 if (udp_client4_sock < 0) {
374 struct sockaddr_in sa;
375 memset(&sa, 0, sizeof(sa));
376 udp_client4_sock = socket(AF_INET, conf->addrinfo->ai_socktype, conf->addrinfo->ai_protocol);
377 if (udp_client4_sock < 0)
378 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
379 if (!bind(udp_client4_sock, (struct sockaddr *)&sa, sizeof(sa)))
380 debugx(1, DBG_ERR, "addserver: failed to bind client socket for server %s", conf->host);
382 conf->servers->sock = udp_client4_sock;
384 if (udp_client6_sock < 0) {
385 struct sockaddr_in6 sa;
386 memset(&sa, 0, sizeof(sa));
387 udp_client6_sock = socket(AF_INET6, conf->addrinfo->ai_socktype, conf->addrinfo->ai_protocol);
388 if (udp_client6_sock < 0)
389 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
391 setsockopt(udp_client6_sock, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&on, sizeof(on));
393 if (!bind(udp_client6_sock, (struct sockaddr *)&sa, sizeof(sa)))
394 debugx(1, DBG_ERR, "addserver: failed to bind client socket for server %s", conf->host);
396 conf->servers->sock = udp_client6_sock;
398 debugx(1, DBG_ERR, "addserver: unsupported address family");
402 conf->servers->sock = -1;
404 pthread_mutex_init(&conf->servers->lock, NULL);
405 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
406 if (!conf->servers->requests)
407 debugx(1, DBG_ERR, "malloc failed");
408 conf->servers->newrq = 0;
409 pthread_mutex_init(&conf->servers->newrq_mutex, NULL);
410 pthread_cond_init(&conf->servers->newrq_cond, NULL);
413 /* exactly one of client and server must be non-NULL */
414 /* should probably take peer list (client(s) or server(s)) as argument instead */
415 /* if *peer == NULL we return who we received from, else require it to be from peer */
416 /* return from in sa if not NULL */
417 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
419 unsigned char buf[65536], *rad;
420 struct sockaddr_storage from;
421 socklen_t fromlen = sizeof(from);
423 struct list_node *node;
426 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
428 debug(DBG_WARN, "radudpget: recv failed");
431 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
434 debug(DBG_WARN, "radudpget: packet too small");
440 debug(DBG_WARN, "radudpget: length too small");
445 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
449 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
453 p = find_conf('U', (struct sockaddr *)&from, NULL, (*client)->conf);
455 p = find_conf('U', (struct sockaddr *)&from, clconfs, NULL);
458 p = find_conf('U', (struct sockaddr *)&from, NULL, (*server)->conf);
460 p = find_conf('U', (struct sockaddr *)&from, srvconfs, NULL);
463 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer, ignoring");
469 debug(DBG_ERR, "radudpget: malloc failed");
473 if (client && !*client) {
474 node = list_first(p->clients);
475 *client = node ? (struct client *)node->data : addclient(p);
480 } else if (server && !*server)
481 *server = p->servers;
485 memcpy(rad, buf, len);
491 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
492 int loc, i, l, n, r = 0;
495 STACK_OF(GENERAL_NAME) *alt;
498 debug(DBG_DBG, "subjectaltnameaddr");
500 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
504 ex = X509_get_ext(cert, loc);
505 alt = X509V3_EXT_d2i(ex);
509 n = sk_GENERAL_NAME_num(alt);
510 for (i = 0; i < n; i++) {
511 gn = sk_GENERAL_NAME_value(alt, i);
512 if (gn->type != GEN_IPADD)
515 v = (char *)ASN1_STRING_data(gn->d.ia5);
516 l = ASN1_STRING_length(gn->d.ia5);
517 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
518 && !memcmp(v, &addr, l)) {
523 GENERAL_NAMES_free(alt);
527 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
528 int loc, i, l, n, r = 0;
531 STACK_OF(GENERAL_NAME) *alt;
534 debug(DBG_DBG, "subjectaltnameregexp");
536 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
540 ex = X509_get_ext(cert, loc);
541 alt = X509V3_EXT_d2i(ex);
545 n = sk_GENERAL_NAME_num(alt);
546 for (i = 0; i < n; i++) {
547 gn = sk_GENERAL_NAME_value(alt, i);
548 if (gn->type != type)
551 v = (char *)ASN1_STRING_data(gn->d.ia5);
552 l = ASN1_STRING_length(gn->d.ia5);
556 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
559 if (memcmp(v, exact, l))
562 s = stringcopy((char *)v, l);
564 debug(DBG_ERR, "malloc failed");
567 if (regexec(regex, s, 0, NULL, 0)) {
576 GENERAL_NAMES_free(alt);
580 int tlsverifycert(SSL *ssl, struct clsrvconf *conf) {
587 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
589 struct in6_addr addr;
591 if (SSL_get_verify_result(ssl) != X509_V_OK) {
592 debug(DBG_ERR, "tlsverifycert: basic validation failed");
593 while ((error = ERR_get_error()))
594 debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
598 cert = SSL_get_peer_certificate(ssl);
600 debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
604 if (inet_pton(AF_INET, conf->host, &addr))
606 else if (inet_pton(AF_INET6, conf->host, &addr))
609 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
613 debug(DBG_DBG, "tlsverifycert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
616 debug(DBG_DBG, "tlsverifycert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
618 nm = X509_get_subject_name(cert);
621 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
624 e = X509_NAME_get_entry(nm, loc);
625 s = X509_NAME_ENTRY_get_data(e);
626 v = (char *) ASN1_STRING_data(s);
627 l = ASN1_STRING_length(s);
631 printfchars(NULL, "cn", NULL, v, l);
633 if (l == strlen(conf->host) && !strncasecmp(conf->host, v, l)) {
635 debug(DBG_DBG, "tlsverifycert: Found cn matching host %s", conf->host);
641 debug(DBG_ERR, "tlsverifycert: cn not matching host %s", conf->host);
645 if (conf->certuriregex) {
646 r = subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex);
648 debug(DBG_DBG, "tlsverifycert: subjectaltname URI not matching regex");
652 debug(DBG_DBG, "tlsverifycert: subjectaltname URI matching regex");
658 void tlsconnect(struct server *server, struct timeval *when, char *text) {
662 debug(DBG_DBG, "tlsconnect called from %s", text);
663 pthread_mutex_lock(&server->lock);
664 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
665 /* already reconnected, nothing to do */
666 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
667 pthread_mutex_unlock(&server->lock);
671 debug(DBG_DBG, "tlsconnect %s", text);
674 gettimeofday(&now, NULL);
675 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
676 if (server->connectionok) {
677 server->connectionok = 0;
679 } else if (elapsed < 5)
681 else if (elapsed < 300) {
682 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
684 } else if (elapsed < 100000) {
685 debug(DBG_INFO, "tlsconnect: sleeping %ds", 600);
688 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
689 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
690 if (server->sock >= 0)
692 if ((server->sock = connecttoserver(server->conf->addrinfo)) < 0) {
693 debug(DBG_ERR, "tlsconnect: connecttoserver failed");
697 SSL_free(server->ssl);
698 server->ssl = SSL_new(server->conf->ssl_ctx);
699 SSL_set_fd(server->ssl, server->sock);
700 if (SSL_connect(server->ssl) > 0 && tlsverifycert(server->ssl, server->conf))
703 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
704 gettimeofday(&server->lastconnecttry, NULL);
705 pthread_mutex_unlock(&server->lock);
708 unsigned char *radtlsget(SSL *ssl) {
710 unsigned char buf[4], *rad;
713 for (total = 0; total < 4; total += cnt) {
714 cnt = SSL_read(ssl, buf + total, 4 - total);
716 debug(DBG_ERR, "radtlsget: connection lost");
717 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
718 /* remote end sent close_notify, send one back */
728 debug(DBG_ERR, "radtlsget: malloc failed");
733 for (; total < len; total += cnt) {
734 cnt = SSL_read(ssl, rad + total, len - total);
736 debug(DBG_ERR, "radtlsget: connection lost");
737 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
738 /* remote end sent close_notify, send one back */
750 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
753 debug(DBG_DBG, "radtlsget: got %d bytes", total);
757 int clientradput(struct server *server, unsigned char *rad) {
761 struct timeval lastconnecttry;
762 struct clsrvconf *conf = server->conf;
765 if (conf->type == 'U') {
766 if (sendto(server->sock, rad, len, 0, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen) >= 0) {
767 debug(DBG_DBG, "clienradput: sent UDP of length %d to %s port %s", len, conf->host, conf->port);
770 debug(DBG_WARN, "clientradput: send failed");
774 lastconnecttry = server->lastconnecttry;
775 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
776 while ((error = ERR_get_error()))
777 debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
778 tlsconnect(server, &lastconnecttry, "clientradput");
779 lastconnecttry = server->lastconnecttry;
782 server->connectionok = 1;
783 debug(DBG_DBG, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
787 int radsign(unsigned char *rad, unsigned char *sec) {
788 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
789 static unsigned char first = 1;
790 static EVP_MD_CTX mdctx;
794 pthread_mutex_lock(&lock);
796 EVP_MD_CTX_init(&mdctx);
800 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
801 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
802 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
803 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
805 pthread_mutex_unlock(&lock);
809 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
810 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
811 static unsigned char first = 1;
812 static EVP_MD_CTX mdctx;
813 unsigned char hash[EVP_MAX_MD_SIZE];
817 pthread_mutex_lock(&lock);
819 EVP_MD_CTX_init(&mdctx);
825 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
826 EVP_DigestUpdate(&mdctx, rad, 4) &&
827 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
828 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
829 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
830 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
832 !memcmp(hash, rad + 4, 16));
833 pthread_mutex_unlock(&lock);
837 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
838 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
839 static unsigned char first = 1;
840 static HMAC_CTX hmacctx;
842 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
844 pthread_mutex_lock(&lock);
846 HMAC_CTX_init(&hmacctx);
850 memcpy(auth, authattr, 16);
851 memset(authattr, 0, 16);
853 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
854 HMAC_Update(&hmacctx, rad, RADLEN(rad));
855 HMAC_Final(&hmacctx, hash, &md_len);
856 memcpy(authattr, auth, 16);
858 debug(DBG_WARN, "message auth computation failed");
859 pthread_mutex_unlock(&lock);
863 if (memcmp(auth, hash, 16)) {
864 debug(DBG_WARN, "message authenticator, wrong value");
865 pthread_mutex_unlock(&lock);
869 pthread_mutex_unlock(&lock);
873 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
874 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
875 static unsigned char first = 1;
876 static HMAC_CTX hmacctx;
882 pthread_mutex_lock(&lock);
884 HMAC_CTX_init(&hmacctx);
888 memset(authattrval, 0, 16);
890 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
891 HMAC_Update(&hmacctx, rad, RADLEN(rad));
892 HMAC_Final(&hmacctx, authattrval, &md_len);
894 debug(DBG_WARN, "message auth computation failed");
895 pthread_mutex_unlock(&lock);
899 pthread_mutex_unlock(&lock);
903 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
905 if (ATTRTYPE(attrs) == type)
907 length -= ATTRLEN(attrs);
908 attrs += ATTRLEN(attrs);
913 void freerqdata(struct request *rq) {
914 if (rq->origusername)
915 free(rq->origusername);
920 void sendrq(struct server *to, struct request *rq) {
924 pthread_mutex_lock(&to->newrq_mutex);
925 /* might simplify if only try nextid, might be ok */
926 for (i = to->nextid; i < MAX_REQUESTS; i++)
927 if (!to->requests[i].buf)
929 if (i == MAX_REQUESTS) {
930 for (i = 0; i < to->nextid; i++)
931 if (!to->requests[i].buf)
933 if (i == to->nextid) {
934 debug(DBG_WARN, "No room in queue, dropping request");
936 pthread_mutex_unlock(&to->newrq_mutex);
941 rq->buf[1] = (char)i;
943 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
944 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
946 pthread_mutex_unlock(&to->newrq_mutex);
950 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
951 to->requests[i] = *rq;
956 debug(DBG_DBG, "signalling client writer");
957 pthread_cond_signal(&to->newrq_cond);
959 pthread_mutex_unlock(&to->newrq_mutex);
962 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
966 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
968 debug(DBG_WARN, "sendreply: failed to sign message");
972 reply = malloc(sizeof(struct reply));
975 debug(DBG_ERR, "sendreply: malloc failed");
978 memset(reply, 0, sizeof(struct reply));
983 pthread_mutex_lock(&to->replyq->mutex);
985 first = list_first(to->replyq->replies) == NULL;
987 if (!list_push(to->replyq->replies, reply)) {
988 pthread_mutex_unlock(&to->replyq->mutex);
991 debug(DBG_ERR, "sendreply: malloc failed");
996 debug(DBG_DBG, "signalling server writer");
997 pthread_cond_signal(&to->replyq->cond);
999 pthread_mutex_unlock(&to->replyq->mutex);
1002 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1003 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1004 static unsigned char first = 1;
1005 static EVP_MD_CTX mdctx;
1006 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1007 unsigned int md_len;
1008 uint8_t i, offset = 0, out[128];
1010 pthread_mutex_lock(&lock);
1012 EVP_MD_CTX_init(&mdctx);
1018 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1019 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1020 !EVP_DigestUpdate(&mdctx, input, 16) ||
1021 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1023 pthread_mutex_unlock(&lock);
1026 for (i = 0; i < 16; i++)
1027 out[offset + i] = hash[i] ^ in[offset + i];
1028 input = out + offset - 16;
1033 memcpy(in, out, len);
1034 pthread_mutex_unlock(&lock);
1038 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1039 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1040 static unsigned char first = 1;
1041 static EVP_MD_CTX mdctx;
1042 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1043 unsigned int md_len;
1044 uint8_t i, offset = 0, out[128];
1046 pthread_mutex_lock(&lock);
1048 EVP_MD_CTX_init(&mdctx);
1054 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1055 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1056 !EVP_DigestUpdate(&mdctx, input, 16) ||
1057 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1059 pthread_mutex_unlock(&lock);
1062 for (i = 0; i < 16; i++)
1063 out[offset + i] = hash[i] ^ in[offset + i];
1064 input = in + offset;
1069 memcpy(in, out, len);
1070 pthread_mutex_unlock(&lock);
1074 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1075 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1076 static unsigned char first = 1;
1077 static EVP_MD_CTX mdctx;
1078 unsigned char hash[EVP_MAX_MD_SIZE];
1079 unsigned int md_len;
1082 pthread_mutex_lock(&lock);
1084 EVP_MD_CTX_init(&mdctx);
1089 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1090 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1091 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1094 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1095 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1096 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1097 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1098 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1099 pthread_mutex_unlock(&lock);
1104 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1107 for (i = 0; i < 16; i++)
1110 for (offset = 16; offset < len; offset += 16) {
1112 printf("text + offset - 16 c(%d): ", offset / 16);
1113 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1115 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1116 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1117 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1118 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1120 pthread_mutex_unlock(&lock);
1124 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1127 for (i = 0; i < 16; i++)
1128 text[offset + i] ^= hash[i];
1132 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1135 pthread_mutex_unlock(&lock);
1139 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1140 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1141 static unsigned char first = 1;
1142 static EVP_MD_CTX mdctx;
1143 unsigned char hash[EVP_MAX_MD_SIZE];
1144 unsigned int md_len;
1148 pthread_mutex_lock(&lock);
1150 EVP_MD_CTX_init(&mdctx);
1155 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1156 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1157 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1160 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1161 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1162 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1163 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1164 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1165 pthread_mutex_unlock(&lock);
1170 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1173 for (i = 0; i < 16; i++)
1174 plain[i] = text[i] ^ hash[i];
1176 for (offset = 16; offset < len; offset += 16) {
1178 printf("text + offset - 16 c(%d): ", offset / 16);
1179 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1181 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1182 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1183 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1184 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1186 pthread_mutex_unlock(&lock);
1190 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1193 for (i = 0; i < 16; i++)
1194 plain[offset + i] = text[offset + i] ^ hash[i];
1197 memcpy(text, plain, len);
1199 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1202 pthread_mutex_unlock(&lock);
1206 struct realm *id2realm(char *id, uint8_t len) {
1207 struct list_node *entry;
1208 struct realm *realm;
1210 for (entry = list_first(realms); entry; entry = list_next(entry)) {
1211 realm = (struct realm *)entry->data;
1212 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1213 debug(DBG_DBG, "found matching realm: %s", realm->name);
1220 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
1223 pthread_mutex_lock(&to->newrq_mutex);
1224 for (i = 0; i < MAX_REQUESTS; i++)
1225 if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
1227 pthread_mutex_unlock(&to->newrq_mutex);
1229 return i < MAX_REQUESTS;
1232 int attrvalidate(unsigned char *attrs, int length) {
1233 while (length > 1) {
1234 if (ATTRLEN(attrs) < 2) {
1235 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1238 length -= ATTRLEN(attrs);
1240 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1243 attrs += ATTRLEN(attrs);
1246 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1250 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1251 if (len < 16 || len > 128 || len % 16) {
1252 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1256 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1257 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1261 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1263 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1264 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1270 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1273 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1274 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1277 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1278 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1284 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1285 char *oldsecret, char *newsecret) {
1286 unsigned char *attr;
1288 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1289 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1290 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1296 /* returns a pointer to the resized attribute value */
1297 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1298 uint8_t *attrs, *attr, vallen;
1302 len = RADLEN(*buf) - 20;
1305 attr = attrget(attrs, len, type);
1309 vallen = ATTRVALLEN(attr);
1310 if (vallen == newvallen)
1313 len += newvallen - vallen;
1314 if (newvallen > vallen) {
1315 new = realloc(*buf, len);
1317 debug(DBG_ERR, "resizeattr: malloc failed");
1326 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1327 attr[1] = newvallen + 2;
1328 ((uint16_t *)*buf)[1] = htons(len + 20);
1332 int rewriteusername(struct request *rq, char *in) {
1333 size_t nmatch = 10, reslen = 0, start = 0;
1334 regmatch_t pmatch[10], *pfield;
1336 unsigned char *result;
1337 char *out = rq->from->conf->rewriteattrreplacement;
1339 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1340 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1344 rq->origusername = stringcopy(in, 0);
1345 if (!rq->origusername)
1348 for (i = start; out[i]; i++) {
1349 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1350 pfield = &pmatch[out[i + 1] - '0'];
1351 if (pfield->rm_so >= 0) {
1352 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1358 reslen += i - start;
1360 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1366 for (i = start; out[i]; i++) {
1367 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1368 pfield = &pmatch[out[i + 1] - '0'];
1369 if (pfield->rm_so >= 0) {
1370 memcpy(result + reslen, out + start, i - start);
1371 reslen += i - start;
1372 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1373 reslen += pfield->rm_eo - pfield->rm_so;
1380 memcpy(result + reslen, out + start, i - start);
1381 reslen += i - start;
1382 memcpy(in, result, reslen);
1387 void acclog(unsigned char *attrs, int length, char *host) {
1388 unsigned char *attr;
1391 attr = attrget(attrs, length, RAD_Attr_User_Name);
1393 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1396 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1397 username[ATTRVALLEN(attr)] = '\0';
1398 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1401 void respondaccounting(struct request *rq) {
1402 unsigned char *resp;
1406 debug(DBG_ERR, "respondstatusserver: malloc failed");
1409 memcpy(resp, rq->buf, 20);
1410 resp[0] = RAD_Accounting_Response;
1413 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1414 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1417 void respondstatusserver(struct request *rq) {
1418 unsigned char *resp;
1422 debug(DBG_ERR, "respondstatusserver: malloc failed");
1425 memcpy(resp, rq->buf, 20);
1426 resp[0] = RAD_Access_Accept;
1429 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1430 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1433 void respondreject(struct request *rq, char *message) {
1434 unsigned char *resp;
1437 if (message && *message)
1438 len += 2 + strlen(message);
1442 debug(DBG_ERR, "respondreject: malloc failed");
1445 memcpy(resp, rq->buf, 20);
1446 resp[0] = RAD_Access_Reject;
1447 *(uint16_t *)(resp + 2) = htons(len);
1448 if (message && *message) {
1449 resp[20] = RAD_Attr_Reply_Message;
1450 resp[21] = len - 20;
1451 memcpy(resp + 22, message, len - 22);
1453 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1456 struct server *realm2server(struct realm *realm) {
1457 struct list_node *entry;
1458 struct server *server, *best = NULL;
1460 for (entry = list_first(realm->srvconfs); entry; entry = list_next(entry)) {
1461 server = ((struct clsrvconf *)entry->data)->servers;
1462 if (!server->connectionok)
1464 if (!server->loststatsrv)
1470 if (server->loststatsrv < best->loststatsrv)
1476 void radsrv(struct request *rq) {
1477 uint8_t code, id, *auth, *attrs, *attr;
1479 struct server *to = NULL;
1481 unsigned char newauth[16];
1482 struct realm *realm = NULL;
1484 code = *(uint8_t *)rq->buf;
1485 id = *(uint8_t *)(rq->buf + 1);
1486 len = RADLEN(rq->buf);
1487 auth = (uint8_t *)(rq->buf + 4);
1489 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1491 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1492 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1498 attrs = rq->buf + 20;
1500 if (!attrvalidate(attrs, len)) {
1501 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1506 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1507 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
1508 debug(DBG_WARN, "radsrv: message authentication failed");
1513 if (code != RAD_Access_Request) {
1515 case RAD_Accounting_Request:
1516 acclog(attrs, len, rq->from->conf->host);
1517 respondaccounting(rq);
1519 case RAD_Status_Server:
1520 respondstatusserver(rq);
1527 /* code == RAD_Access_Request */
1528 attr = attrget(attrs, len, RAD_Attr_User_Name);
1530 debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1534 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1535 username[ATTRVALLEN(attr)] = '\0';
1537 if (rq->from->conf->rewriteattrregex) {
1538 if (!rewriteusername(rq, username)) {
1539 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1543 len = RADLEN(rq->buf) - 20;
1544 auth = (uint8_t *)(rq->buf + 4);
1545 attrs = rq->buf + 20;
1548 if (rq->origusername)
1549 debug(DBG_DBG, "Access Request with username: %s (originally %s)", username, rq->origusername);
1551 debug(DBG_DBG, "Access Request with username: %s", username);
1553 realm = id2realm(username, strlen(username));
1555 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1560 to = realm2server(realm);
1561 if (to && rqinqueue(to, rq->from, id)) {
1562 debug(DBG_INFO, "radsrv: already got request from host %s with id %d, ignoring", rq->from->conf->host, id);
1568 if (realm->message) {
1569 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, username);
1570 respondreject(rq, realm->message);
1576 if (!RAND_bytes(newauth, 16)) {
1577 debug(DBG_WARN, "radsrv: failed to generate random auth");
1583 printfchars(NULL, "auth", "%02x ", auth, 16);
1586 attr = attrget(attrs, len, RAD_Attr_User_Password);
1588 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1589 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1595 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1597 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1598 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1605 memcpy(rq->origauth, auth, 16);
1606 memcpy(auth, newauth, 16);
1610 int replyh(struct server *server, unsigned char *buf) {
1611 struct client *from;
1614 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
1615 struct sockaddr_storage fromsa;
1618 server->connectionok = 1;
1619 server->loststatsrv = 0;
1621 i = buf[1]; /* i is the id */
1624 case RAD_Access_Accept:
1625 debug(DBG_DBG, "got Access Accept with id %d", i);
1627 case RAD_Access_Reject:
1628 debug(DBG_DBG, "got Access Reject with id %d", i);
1630 case RAD_Access_Challenge:
1631 debug(DBG_DBG, "got Access Challenge with id %d", i);
1634 debug(DBG_INFO, "replyh: discarding, only accept access accept, access reject and access challenge messages");
1638 rq = server->requests + i;
1640 pthread_mutex_lock(&server->newrq_mutex);
1641 if (!rq->buf || !rq->tries) {
1642 pthread_mutex_unlock(&server->newrq_mutex);
1643 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
1648 pthread_mutex_unlock(&server->newrq_mutex);
1649 debug(DBG_INFO, "replyh: already received, ignoring reply");
1653 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
1654 pthread_mutex_unlock(&server->newrq_mutex);
1655 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
1660 len = RADLEN(buf) - 20;
1663 if (!attrvalidate(attrs, len)) {
1664 pthread_mutex_unlock(&server->newrq_mutex);
1665 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
1669 /* Message Authenticator */
1670 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1672 if (ATTRVALLEN(messageauth) != 16) {
1673 pthread_mutex_unlock(&server->newrq_mutex);
1674 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
1677 memcpy(tmp, buf + 4, 16);
1678 memcpy(buf + 4, rq->buf + 4, 16);
1679 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
1680 pthread_mutex_unlock(&server->newrq_mutex);
1681 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
1684 memcpy(buf + 4, tmp, 16);
1685 debug(DBG_DBG, "replyh: message auth ok");
1688 if (*rq->buf == RAD_Status_Server) {
1690 pthread_mutex_unlock(&server->newrq_mutex);
1691 debug(DBG_INFO, "replyh: got status server response from %s", server->conf->host);
1696 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1697 if (ATTRVALLEN(attr) <= 4)
1700 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
1703 sublen = ATTRVALLEN(attr) - 4;
1704 subattrs = ATTRVAL(attr) + 4;
1705 if (!attrvalidate(subattrs, sublen) ||
1706 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1707 rq, server->conf->secret, from->conf->secret) ||
1708 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1709 rq, server->conf->secret, from->conf->secret))
1713 pthread_mutex_unlock(&server->newrq_mutex);
1714 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1718 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject) {
1719 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
1720 /* we know the attribute exists */
1721 memcpy(tmp, ATTRVAL(attr), ATTRVALLEN(attr));
1722 tmp[ATTRVALLEN(attr)] = '\0';
1724 case RAD_Access_Accept:
1725 if (rq->origusername)
1726 debug(DBG_INFO, "Access Accept for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1728 debug(DBG_INFO, "Access Accept for %s from %s", tmp, server->conf->host);
1730 case RAD_Access_Reject:
1731 if (rq->origusername)
1732 debug(DBG_INFO, "Access Reject for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1734 debug(DBG_INFO, "Access Reject for %s from %s", tmp, server->conf->host);
1739 buf[1] = (char)rq->origid;
1740 memcpy(buf + 4, rq->origauth, 16);
1742 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1745 if (rq->origusername) {
1746 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
1748 pthread_mutex_unlock(&server->newrq_mutex);
1749 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1752 memcpy(username, rq->origusername, strlen(rq->origusername));
1753 len = RADLEN(buf) - 20;
1756 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1760 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
1761 pthread_mutex_unlock(&server->newrq_mutex);
1762 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
1765 debug(DBG_DBG, "replyh: computed messageauthattr");
1768 if (from->conf->type == 'U')
1769 fromsa = rq->fromsa;
1770 /* once we set received = 1, rq may be reused */
1772 pthread_mutex_unlock(&server->newrq_mutex);
1774 debug(DBG_DBG, "replyh: giving packet back to where it came from");
1775 sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
1779 void *udpclientrd(void *arg) {
1780 struct server *server;
1782 int *s = (int *)arg;
1786 buf = radudpget(*s, NULL, &server, NULL);
1787 if (!replyh(server, buf))
1792 void *tlsclientrd(void *arg) {
1793 struct server *server = (struct server *)arg;
1795 struct timeval lastconnecttry;
1798 /* yes, lastconnecttry is really necessary */
1799 lastconnecttry = server->lastconnecttry;
1800 buf = radtlsget(server->ssl);
1802 tlsconnect(server, &lastconnecttry, "clientrd");
1806 if (!replyh(server, buf))
1811 void *clientwr(void *arg) {
1812 struct server *server = (struct server *)arg;
1814 pthread_t tlsclientrdth;
1817 struct timeval now, lastsend;
1818 struct timespec timeout;
1819 struct request statsrvrq;
1820 unsigned char statsrvbuf[38];
1822 memset(&timeout, 0, sizeof(struct timespec));
1824 if (server->conf->statusserver) {
1825 memset(&statsrvrq, 0, sizeof(struct request));
1826 memset(statsrvbuf, 0, sizeof(statsrvbuf));
1827 statsrvbuf[0] = RAD_Status_Server;
1829 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
1830 statsrvbuf[21] = 18;
1831 gettimeofday(&lastsend, NULL);
1834 if (server->conf->type == 'U') {
1835 server->connectionok = 1;
1837 tlsconnect(server, NULL, "new client");
1838 server->connectionok = 1;
1839 if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server))
1840 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
1844 pthread_mutex_lock(&server->newrq_mutex);
1845 if (!server->newrq) {
1846 gettimeofday(&now, NULL);
1847 if (server->conf->statusserver) {
1848 /* random 0-7 seconds */
1849 RAND_bytes(&rnd, 1);
1851 if (!timeout.tv_sec || timeout.tv_sec - now.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
1852 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
1854 if (timeout.tv_sec) {
1855 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1856 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1859 debug(DBG_DBG, "clientwr: waiting for new request");
1860 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1863 if (server->newrq) {
1864 debug(DBG_DBG, "clientwr: got new request");
1867 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1868 pthread_mutex_unlock(&server->newrq_mutex);
1870 for (i = 0; i < MAX_REQUESTS; i++) {
1871 pthread_mutex_lock(&server->newrq_mutex);
1872 while (i < MAX_REQUESTS && !server->requests[i].buf)
1874 if (i == MAX_REQUESTS) {
1875 pthread_mutex_unlock(&server->newrq_mutex);
1878 rq = server->requests + i;
1881 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
1883 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
1885 /* setting this to NULL means that it can be reused */
1888 pthread_mutex_unlock(&server->newrq_mutex);
1892 gettimeofday(&now, NULL);
1893 if (now.tv_sec < rq->expiry.tv_sec) {
1894 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1895 timeout.tv_sec = rq->expiry.tv_sec;
1896 pthread_mutex_unlock(&server->newrq_mutex);
1900 if (rq->tries == (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
1901 ? 1 : REQUEST_RETRIES)) {
1902 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1903 if (*rq->buf == RAD_Status_Server) {
1904 debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->conf->host);
1905 if (server->loststatsrv < 255)
1906 server->loststatsrv++;
1909 /* setting this to NULL means that it can be reused */
1911 pthread_mutex_unlock(&server->newrq_mutex);
1914 pthread_mutex_unlock(&server->newrq_mutex);
1916 rq->expiry.tv_sec = now.tv_sec +
1917 (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
1918 ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
1919 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1920 timeout.tv_sec = rq->expiry.tv_sec;
1922 clientradput(server, server->requests[i].buf);
1923 gettimeofday(&lastsend, NULL);
1925 if (server->conf->statusserver) {
1926 gettimeofday(&now, NULL);
1927 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
1928 if (!RAND_bytes(statsrvbuf + 4, 16)) {
1929 debug(DBG_WARN, "clientwr: failed to generate random auth");
1932 statsrvrq.buf = malloc(sizeof(statsrvbuf));
1933 if (!statsrvrq.buf) {
1934 debug(DBG_ERR, "clientwr: malloc failed");
1937 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
1938 debug(DBG_DBG, "clientwr: sending status server to %s", server->conf->host);
1939 lastsend.tv_sec = now.tv_sec;
1940 sendrq(server, &statsrvrq);
1946 void *udpserverwr(void *arg) {
1947 struct replyq *replyq = udp_server_replyq;
1948 struct reply *reply;
1951 pthread_mutex_lock(&replyq->mutex);
1952 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
1953 debug(DBG_DBG, "udp server writer, waiting for signal");
1954 pthread_cond_wait(&replyq->cond, &replyq->mutex);
1955 debug(DBG_DBG, "udp server writer, got signal");
1957 pthread_mutex_unlock(&replyq->mutex);
1959 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
1960 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
1961 debug(DBG_WARN, "sendudp: send failed");
1967 void *udpserverrd(void *arg) {
1969 pthread_t udpserverwrth;
1971 if ((udp_server_sock = bindtoaddr(udp_server_listen->addrinfo)) < 0)
1972 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
1974 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
1975 udp_server_listen->host ? udp_server_listen->host : "*", udp_server_listen->port);
1977 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
1978 debugx(1, DBG_ERR, "pthread_create failed");
1981 memset(&rq, 0, sizeof(struct request));
1982 rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
1987 void *udpaccserverrd(void *arg) {
1990 if ((udp_accserver_sock = bindtoaddr(udp_accserver_listen->addrinfo)) < 0)
1991 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
1993 debug(DBG_WARN, "udpaccserverrd: listening for UDP on %s:%s",
1994 udp_accserver_listen->host ? udp_accserver_listen->host : "*", udp_accserver_listen->port);
1997 memset(&rq, 0, sizeof(struct request));
1998 rq.buf = radudpget(udp_accserver_sock, &rq.from, NULL, &rq.fromsa);
1999 if (*(uint8_t *)rq.buf == RAD_Accounting_Request) {
2003 debug(DBG_INFO, "udpaccserverrd: got something other than accounting-request, ignoring");
2008 void *tlsserverwr(void *arg) {
2010 unsigned long error;
2011 struct client *client = (struct client *)arg;
2012 struct replyq *replyq;
2013 struct reply *reply;
2015 debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
2016 replyq = client->replyq;
2018 pthread_mutex_lock(&replyq->mutex);
2019 while (!list_first(replyq->replies)) {
2021 debug(DBG_DBG, "tls server writer, waiting for signal");
2022 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2023 debug(DBG_DBG, "tls server writer, got signal");
2026 /* ssl might have changed while waiting */
2027 pthread_mutex_unlock(&replyq->mutex);
2028 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2032 reply = (struct reply *)list_shift(replyq->replies);
2033 pthread_mutex_unlock(&replyq->mutex);
2034 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2036 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
2037 cnt, RADLEN(reply->buf));
2039 while ((error = ERR_get_error()))
2040 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2046 void *tlsserverrd(void *arg) {
2048 unsigned long error;
2050 struct client *client = (struct client *)arg;
2051 pthread_t tlsserverwrth;
2054 debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2057 if (SSL_accept(ssl) <= 0) {
2058 while ((error = ERR_get_error()))
2059 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2060 debug(DBG_ERR, "SSL_accept failed");
2063 if (tlsverifycert(client->ssl, client->conf)) {
2064 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2065 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2069 memset(&rq, 0, sizeof(struct request));
2070 rq.buf = radtlsget(client->ssl);
2073 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2077 debug(DBG_ERR, "tlsserverrd: connection lost");
2078 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2080 pthread_mutex_lock(&client->replyq->mutex);
2081 pthread_cond_signal(&client->replyq->cond);
2082 pthread_mutex_unlock(&client->replyq->mutex);
2083 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2084 pthread_join(tlsserverwrth, NULL);
2088 s = SSL_get_fd(ssl);
2090 shutdown(s, SHUT_RDWR);
2092 debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->conf->host);
2093 removeclient(client);
2098 pthread_t tlsserverth;
2100 struct sockaddr_storage from;
2101 size_t fromlen = sizeof(from);
2102 struct clsrvconf *conf;
2103 struct client *client;
2105 if ((s = bindtoaddr(tcp_server_listen->addrinfo)) < 0)
2106 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
2109 debug(DBG_WARN, "listening for incoming TCP on %s:%s",
2110 tcp_server_listen->host ? tcp_server_listen->host : "*", tcp_server_listen->port);
2113 snew = accept(s, (struct sockaddr *)&from, &fromlen);
2115 debug(DBG_WARN, "accept failed");
2118 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2120 conf = find_conf('T', (struct sockaddr *)&from, clconfs, NULL);
2122 debug(DBG_WARN, "ignoring request, not a known TLS client");
2123 shutdown(snew, SHUT_RDWR);
2128 client = addclient(conf);
2131 debug(DBG_WARN, "Failed to create new client instance");
2132 shutdown(snew, SHUT_RDWR);
2136 client->ssl = SSL_new(client->conf->ssl_ctx);
2137 SSL_set_fd(client->ssl, snew);
2138 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
2139 debug(DBG_ERR, "tlslistener: pthread_create failed");
2140 SSL_free(client->ssl);
2141 removeclient(client);
2142 shutdown(snew, SHUT_RDWR);
2146 pthread_detach(tlsserverth);
2151 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
2155 unsigned long error;
2157 if (!certfile || !certkeyfile)
2158 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2160 if (!cacertfile && !cacertpath)
2161 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2164 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2165 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2166 for (i = 0; i < CRYPTO_num_locks(); i++) {
2167 ssl_lock_count[i] = 0;
2168 pthread_mutex_init(&ssl_locks[i], NULL);
2170 CRYPTO_set_id_callback(ssl_thread_id);
2171 CRYPTO_set_locking_callback(ssl_locking_callback);
2173 SSL_load_error_strings();
2176 while (!RAND_status()) {
2177 time_t t = time(NULL);
2178 pid_t pid = getpid();
2179 RAND_seed((unsigned char *)&t, sizeof(time_t));
2180 RAND_seed((unsigned char *)&pid, sizeof(pid));
2183 ctx = SSL_CTX_new(TLSv1_method());
2185 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2186 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2188 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2189 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2190 !SSL_CTX_check_private_key(ctx) ||
2191 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2192 while ((error = ERR_get_error()))
2193 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2194 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2197 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2198 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2200 new = malloc(sizeof(struct tls));
2201 if (!new || !list_push(tlsconfs, new))
2202 debugx(1, DBG_ERR, "malloc failed");
2204 memset(new, 0, sizeof(struct tls));
2205 new->name = stringcopy(value, 0);
2207 debugx(1, DBG_ERR, "malloc failed");
2210 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2214 struct list_node *entry;
2217 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2218 t = (struct tls *)entry->data;
2222 SSL_CTX_free(t->ctx);
2224 list_destroy(tlsconfs);
2228 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2229 struct list_node *entry;
2230 struct tls *t, *t1 = NULL, *t2 = NULL;
2232 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2233 t = (struct tls *)entry->data;
2234 if (!strcasecmp(t->name, alt1)) {
2238 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2249 void addrealm(char *value, char **servers, char *message) {
2251 struct realm *realm;
2252 char *s, *regex = NULL;
2253 struct list_node *entry;
2254 struct clsrvconf *conf;
2256 if (*value == '/') {
2257 /* regexp, remove optional trailing / if present */
2258 if (value[strlen(value) - 1] == '/')
2259 value[strlen(value) - 1] = '\0';
2261 /* not a regexp, let us make it one */
2262 if (*value == '*' && !value[1])
2263 regex = stringcopy(".*", 0);
2265 for (n = 0, s = value; *s;)
2268 regex = malloc(strlen(value) + n + 3);
2271 for (n = 1, s = value; *s; s++) {
2281 debugx(1, DBG_ERR, "malloc failed");
2282 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2285 realm = malloc(sizeof(struct realm));
2287 debugx(1, DBG_ERR, "malloc failed");
2289 memset(realm, 0, sizeof(struct realm));
2290 realm->name = stringcopy(value, 0);
2292 debugx(1, DBG_ERR, "malloc failed");
2293 if (message && strlen(message) > 253)
2294 debugx(1, DBG_ERR, "ReplyMessage can be at most 253 bytes");
2295 realm->message = message;
2297 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB))
2298 debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2302 if (servers && *servers) {
2303 realm->srvconfs = list_create();
2304 if (!realm->srvconfs)
2305 debugx(1, DBG_ERR, "malloc failed");
2306 for (n = 0; servers[n]; n++) {
2307 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2308 conf = (struct clsrvconf *)entry->data;
2309 if (!strcasecmp(servers[n], conf->name))
2313 debugx(1, DBG_ERR, "addrealm failed, no server %s", servers[n]);
2314 if (!list_push(realm->srvconfs, conf))
2315 debugx(1, DBG_ERR, "malloc failed");
2316 debug(DBG_DBG, "addrealm: added server %s for realm %s", conf->name, value);
2319 realm->srvconfs = NULL;
2321 if (!list_push(realms, realm))
2322 debugx(1, DBG_ERR, "malloc failed");
2323 debug(DBG_DBG, "addrealm: added realm %s", value);
2326 char *parsehostport(char *s, struct clsrvconf *conf) {
2331 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
2335 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
2337 debugx(1, DBG_ERR, "no ] matching initial [");
2341 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
2344 debugx(1, DBG_ERR, "missing host/address");
2346 conf->host = stringcopy(field, p - field);
2349 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
2350 debugx(1, DBG_ERR, "unexpected character after ]");
2353 /* port number or service name is specified */;
2355 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
2357 debugx(1, DBG_ERR, "syntax error, : but no following port");
2358 conf->port = stringcopy(field, p - field);
2360 conf->port = stringcopy(conf->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT, 0);
2364 FILE *openconfigfile(const char *filename) {
2366 char pathname[100], *base = NULL;
2368 f = fopen(filename, "r");
2370 debug(DBG_DBG, "reading config file %s", filename);
2374 if (strlen(filename) + 1 <= sizeof(pathname)) {
2375 /* basename() might modify the string */
2376 strcpy(pathname, filename);
2377 base = basename(pathname);
2378 f = fopen(base, "r");
2382 debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
2384 debug(DBG_DBG, "reading config file %s", base);
2388 struct clsrvconf *server_create(char type, char *lconf) {
2389 struct clsrvconf *conf;
2391 conf = malloc(sizeof(struct clsrvconf));
2393 debugx(1, DBG_ERR, "malloc failed");
2394 memset(conf, 0, sizeof(struct clsrvconf));
2397 parsehostport(lconf, conf);
2398 if (!strcmp(conf->host, "*")) {
2403 conf->port = stringcopy(type == 'T' ? DEFAULT_TLS_PORT : DEFAULT_UDP_PORT, 0);
2404 if (!resolvepeer(conf, AI_PASSIVE))
2405 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2409 /* returns NULL on error, where to continue parsing if token and ok. E.g. "" will return token with empty string */
2410 char *strtokenquote(char *s, char **token, char *del, char *quote, char *comment) {
2411 char *t = s, *q, *r;
2413 if (!t || !token || !del)
2415 while (*t && strchr(del, *t))
2417 if (!*t || (comment && strchr(comment, *t))) {
2419 return t + 1; /* needs to be non-NULL, but value doesn't matter */
2421 if (quote && (q = strchr(quote, *t))) {
2424 while (*t && *t != *q)
2426 if (!*t || (t[1] && !strchr(del, t[1])))
2434 while (*t && !strchr(del, *t))
2440 /* Parses config with following syntax:
2443 * option-name = value
2445 * option-name value {
2446 * option-name [=] value
2450 void getgeneralconfig(FILE *f, char *block, ...) {
2453 /* initialise lots of stuff to avoid stupid compiler warnings */
2454 char *tokens[3], *s, *opt = NULL, *val = NULL, *word, *optval, **str = NULL, ***mstr = NULL;
2455 int type = 0, tcount, conftype = 0, n;
2456 void (*cbk)(FILE *, char *, char *, char *) = NULL;
2458 while (fgets(line, 1024, f)) {
2460 for (tcount = 0; tcount < 3; tcount++) {
2461 s = strtokenquote(s, &tokens[tcount], " \t\r\n", "\"'", tcount ? NULL : "#");
2463 debugx(1, DBG_ERR, "Syntax error in line starting with: %s", line);
2464 if (!tokens[tcount])
2467 if (!tcount || **tokens == '#')
2470 if (**tokens == '}') {
2473 debugx(1, DBG_ERR, "configuration error, found } with no matching {");
2480 conftype = CONF_STR;
2483 if (tokens[1][0] == '=' && tokens[1][1] == '\0') {
2486 conftype = CONF_STR;
2489 if (tokens[2][0] == '{' && tokens[2][1] == '\0') {
2492 conftype = CONF_CBK;
2498 debugx(1, DBG_ERR, "configuration error in block %s, line starting with %s", block, tokens[0]);
2499 debugx(1, DBG_ERR, "configuration error, syntax error in line starting with %s", tokens[0]);
2503 debugx(1, DBG_ERR, "configuration error, option %s needs a non-empty value", opt);
2505 va_start(ap, block);
2506 while ((word = va_arg(ap, char *))) {
2507 type = va_arg(ap, int);
2510 str = va_arg(ap, char **);
2512 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2515 mstr = va_arg(ap, char ***);
2517 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2520 cbk = va_arg(ap, void (*)(FILE *, char *, char *, char *));
2523 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2525 if (!strcasecmp(opt, word))
2532 debugx(1, DBG_ERR, "configuration error in block %s, unknown option %s", block, opt);
2533 debugx(1, DBG_ERR, "configuration error, unknown option %s", opt);
2536 if (((type == CONF_STR || type == CONF_MSTR) && conftype != CONF_STR) ||
2537 (type == CONF_CBK && conftype != CONF_CBK)) {
2539 debugx(1, DBG_ERR, "configuration error in block %s, wrong syntax for option %s", block, opt);
2540 debugx(1, DBG_ERR, "configuration error, wrong syntax for option %s", opt);
2546 debug(DBG_DBG, "getgeneralconfig: block %s: %s = %s", block, opt, val);
2548 debug(DBG_DBG, "getgeneralconfig: %s = %s", opt, val);
2550 debugx(1, DBG_ERR, "configuration error, option %s already set to %s", opt, *str);
2551 *str = stringcopy(val, 0);
2553 debugx(1, DBG_ERR, "malloc failed");
2557 debug(DBG_DBG, "getgeneralconfig: block %s: %s = %s", block, opt, val);
2559 debug(DBG_DBG, "getgeneralconfig: %s = %s", opt, val);
2561 for (n = 0; (*mstr)[n]; n++);
2564 *mstr = realloc(*mstr, sizeof(char *) * (n + 2));
2566 debugx(1, DBG_ERR, "malloc failed");
2567 (*mstr)[n] = stringcopy(val, 0);
2568 (*mstr)[n + 1] = NULL;
2571 optval = malloc(strlen(opt) + strlen(val) + 2);
2573 debugx(1, DBG_ERR, "malloc failed");
2574 sprintf(optval, "%s %s", opt, val);
2575 cbk(f, optval, opt, val);
2579 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2584 int addmatchcertattr(struct clsrvconf *conf, char *matchcertattr) {
2587 v = matchcertattr + 20;
2588 if (strncasecmp(matchcertattr, "SubjectAltName:URI:/", 20) || !*v)
2590 /* regexp, remove optional trailing / if present */
2591 if (v[strlen(v) - 1] == '/')
2592 v[strlen(v) - 1] = '\0';
2596 conf->certuriregex = malloc(sizeof(regex_t));
2597 if (!conf->certuriregex) {
2598 debug(DBG_ERR, "malloc failed");
2601 if (regcomp(conf->certuriregex, v, REG_ICASE | REG_NOSUB)) {
2602 free(conf->certuriregex);
2603 conf->certuriregex = NULL;
2604 debug(DBG_ERR, "failed to compile regular expression %s", v);
2610 int addrewriteattr(struct clsrvconf *conf, char *rewriteattr) {
2613 v = rewriteattr + 11;
2614 if (strncasecmp(rewriteattr, "User-Name:/", 11) || !*v)
2616 /* regexp, remove optional trailing / if present */
2617 if (v[strlen(v) - 1] == '/')
2618 v[strlen(v) - 1] = '\0';
2626 conf->rewriteattrregex = malloc(sizeof(regex_t));
2627 if (!conf->rewriteattrregex) {
2628 debug(DBG_ERR, "malloc failed");
2632 conf->rewriteattrreplacement = stringcopy(w, 0);
2633 if (!conf->rewriteattrreplacement) {
2634 free(conf->rewriteattrregex);
2635 conf->rewriteattrregex = NULL;
2639 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
2640 free(conf->rewriteattrregex);
2641 conf->rewriteattrregex = NULL;
2642 free(conf->rewriteattrreplacement);
2643 conf->rewriteattrreplacement = NULL;
2644 debug(DBG_ERR, "failed to compile regular expression %s", v);
2651 void confclient_cb(FILE *f, char *block, char *opt, char *val) {
2652 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *rewriteattr = NULL;
2653 struct clsrvconf *conf;
2655 debug(DBG_DBG, "confclient_cb called for %s", block);
2657 conf = malloc(sizeof(struct clsrvconf));
2658 if (!conf || !list_push(clconfs, conf))
2659 debugx(1, DBG_ERR, "malloc failed");
2660 memset(conf, 0, sizeof(struct clsrvconf));
2662 getgeneralconfig(f, block,
2663 "type", CONF_STR, &type,
2664 "host", CONF_STR, &conf->host,
2665 "secret", CONF_STR, &conf->secret,
2666 "tls", CONF_STR, &tls,
2667 "matchcertificateattribute", CONF_STR, &matchcertattr,
2668 "rewriteattribute", CONF_STR, &rewriteattr,
2672 /* leave conf->name to be NULL for clients */
2674 conf->host = stringcopy(val, 0);
2676 if (type && !strcasecmp(type, "udp")) {
2679 } else if (type && !strcasecmp(type, "tls")) {
2680 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultclient", "default");
2682 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2683 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2684 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2688 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2693 free(matchcertattr);
2696 if (!addrewriteattr(conf, rewriteattr))
2697 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2701 if (!resolvepeer(conf, 0))
2702 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2704 if (!conf->secret) {
2705 if (conf->type == 'U')
2706 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2707 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2711 void confserver_cb(FILE *f, char *block, char *opt, char *val) {
2712 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *statusserver = NULL;
2713 struct clsrvconf *conf;
2715 debug(DBG_DBG, "confserver_cb called for %s", block);
2717 conf = malloc(sizeof(struct clsrvconf));
2718 if (!conf || !list_push(srvconfs, conf))
2719 debugx(1, DBG_ERR, "malloc failed");
2720 memset(conf, 0, sizeof(struct clsrvconf));
2722 getgeneralconfig(f, block,
2723 "type", CONF_STR, &type,
2724 "host", CONF_STR, &conf->host,
2725 "port", CONF_STR, &conf->port,
2726 "secret", CONF_STR, &conf->secret,
2727 "tls", CONF_STR, &tls,
2728 "matchcertificateattribute", CONF_STR, &matchcertattr,
2729 "StatusServer", CONF_STR, &statusserver,
2733 conf->name = stringcopy(val, 0);
2735 conf->host = stringcopy(val, 0);
2737 if (type && !strcasecmp(type, "udp")) {
2741 conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
2742 } else if (type && !strcasecmp(type, "tls")) {
2743 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultserver", "default");
2745 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2746 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2747 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2749 conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
2753 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2758 free(matchcertattr);
2760 if (!resolvepeer(conf, 0))
2761 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2763 if (!conf->secret) {
2764 if (conf->type == 'U')
2765 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2766 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2770 if (!strcasecmp(statusserver, "on"))
2771 conf->statusserver = 1;
2772 else if (strcasecmp(statusserver, "off"))
2773 debugx(1, DBG_ERR, "error in block %s, StatusServer is %s, must be on or off", block, statusserver);
2778 void confrealm_cb(FILE *f, char *block, char *opt, char *val) {
2779 char **servers = NULL, *msg = NULL;
2781 debug(DBG_DBG, "confrealm_cb called for %s", block);
2783 getgeneralconfig(f, block,
2784 "server", CONF_MSTR, &servers,
2785 "ReplyMessage", CONF_STR, &msg,
2789 addrealm(val, servers, msg);
2793 void conftls_cb(FILE *f, char *block, char *opt, char *val) {
2794 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
2796 debug(DBG_DBG, "conftls_cb called for %s", block);
2798 getgeneralconfig(f, block,
2799 "CACertificateFile", CONF_STR, &cacertfile,
2800 "CACertificatePath", CONF_STR, &cacertpath,
2801 "CertificateFile", CONF_STR, &certfile,
2802 "CertificateKeyFile", CONF_STR, &certkeyfile,
2803 "CertificateKeyPassword", CONF_STR, &certkeypwd,
2807 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
2815 void getmainconfig(const char *configfile) {
2817 char *loglevel = NULL;
2819 f = openconfigfile(configfile);
2820 memset(&options, 0, sizeof(options));
2822 clconfs = list_create();
2824 debugx(1, DBG_ERR, "malloc failed");
2826 srvconfs = list_create();
2828 debugx(1, DBG_ERR, "malloc failed");
2830 realms = list_create();
2832 debugx(1, DBG_ERR, "malloc failed");
2834 tlsconfs = list_create();
2836 debugx(1, DBG_ERR, "malloc failed");
2838 getgeneralconfig(f, NULL,
2839 "ListenUDP", CONF_STR, &options.listenudp,
2840 "ListenTCP", CONF_STR, &options.listentcp,
2841 "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
2842 "LogLevel", CONF_STR, &loglevel,
2843 "LogDestination", CONF_STR, &options.logdestination,
2844 "Client", CONF_CBK, confclient_cb,
2845 "Server", CONF_CBK, confserver_cb,
2846 "Realm", CONF_CBK, confrealm_cb,
2847 "TLS", CONF_CBK, conftls_cb,
2854 if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
2855 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
2856 options.loglevel = *loglevel - '0';
2861 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *loglevel, char **configfile) {
2864 while ((c = getopt(argc, argv, "c:d:fv")) != -1) {
2867 *configfile = optarg;
2870 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
2871 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
2872 *loglevel = *optarg - '0';
2878 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
2883 if (!(argc - optind))
2887 debug(DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -v ]", argv[0]);
2891 int main(int argc, char **argv) {
2892 pthread_t udpserverth, udpaccserverth, udpclient4rdth, udpclient6rdth;
2893 struct list_node *entry;
2894 uint8_t foreground = 0, loglevel = 0;
2895 char *configfile = NULL;
2897 debug_init("radsecproxy");
2898 debug_set_level(DEBUG_LEVEL);
2899 getargs(argc, argv, &foreground, &loglevel, &configfile);
2901 debug_set_level(loglevel);
2902 getmainconfig(configfile ? configfile : CONFIG_MAIN);
2904 options.loglevel = loglevel;
2905 else if (options.loglevel)
2906 debug_set_level(options.loglevel);
2908 options.logdestination = NULL;
2910 if (!options.logdestination)
2911 options.logdestination = "x-syslog:///";
2912 debug_set_destination(options.logdestination);
2915 if (!list_first(clconfs))
2916 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
2917 if (!list_first(srvconfs))
2918 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
2919 if (!list_first(realms))
2920 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
2922 if (!foreground && (daemon(0, 0) < 0))
2923 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
2925 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
2927 if (client_udp_count) {
2928 udp_server_listen = server_create('U', options.listenudp);
2929 udp_server_replyq = newreplyq();
2930 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
2931 debugx(1, DBG_ERR, "pthread_create failed");
2932 if (options.listenaccudp) {
2933 udp_accserver_listen = server_create('U', options.listenaccudp);
2934 if (pthread_create(&udpaccserverth, NULL, udpaccserverrd, NULL))
2935 debugx(1, DBG_ERR, "pthread_create failed");
2939 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2940 addserver((struct clsrvconf *)entry->data);
2941 if (pthread_create(&((struct clsrvconf *)entry->data)->servers->clientth, NULL, clientwr,
2942 (void *)((struct clsrvconf *)entry->data)->servers))
2943 debugx(1, DBG_ERR, "pthread_create failed");
2946 if (udp_client4_sock >= 0)
2947 if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
2948 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
2949 if (udp_client6_sock >= 0)
2950 if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
2951 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
2953 if (client_tls_count) {
2954 tcp_server_listen = server_create('T', options.listentcp);
2955 return tlslistener();
2958 /* just hang around doing nothing, anything to do here? */