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 *srcudpres = NULL;
62 static struct clsrvconf *srctcpres = NULL;
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, *res;
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;
165 if (!conf->host && !conf->port) {
166 /* getaddrinfo() doesn't like host and port to be NULL */
167 if (getaddrinfo(conf->host, DEFAULT_UDP_PORT, &hints, &addrinfo)) {
168 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
171 for (res = addrinfo; res; res = res->ai_next) {
172 switch (res->ai_family) {
174 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
177 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
183 hints.ai_flags |= AI_NUMERICHOST;
184 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
185 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host, conf->port);
190 switch (addrinfo->ai_family) {
193 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
194 freeaddrinfo(addrinfo);
201 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
202 freeaddrinfo(addrinfo);
205 conf->prefixlen = plen;
207 conf->prefixlen = 255;
210 freeaddrinfo(conf->addrinfo);
211 conf->addrinfo = addrinfo;
215 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
217 struct addrinfo *res;
219 for (res = addrinfo; res; res = res->ai_next) {
220 if (family != AF_UNSPEC && family != res->ai_family)
222 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
224 debug(DBG_WARN, "bindtoaddr: socket failed");
228 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
231 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
234 if (!bind(s, res->ai_addr, res->ai_addrlen))
236 debug(DBG_WARN, "bindtoaddr: bind failed");
242 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
247 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
251 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
253 debugx(1, DBG_ERR, "no ] matching initial [");
257 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
260 debugx(1, DBG_ERR, "missing host/address");
262 conf->host = stringcopy(field, p - field);
265 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
266 debugx(1, DBG_ERR, "unexpected character after ]");
269 /* port number or service name is specified */;
271 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
273 debugx(1, DBG_ERR, "syntax error, : but no following port");
274 conf->port = stringcopy(field, p - field);
276 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
280 struct clsrvconf *resolve_hostport(char type, char *lconf, char *default_port) {
281 struct clsrvconf *conf;
283 conf = malloc(sizeof(struct clsrvconf));
285 debugx(1, DBG_ERR, "malloc failed");
286 memset(conf, 0, sizeof(struct clsrvconf));
289 parsehostport(lconf, conf, default_port);
290 if (!strcmp(conf->host, "*")) {
295 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
296 if (!resolvepeer(conf, AI_PASSIVE))
297 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
301 int connecttcp(struct addrinfo *addrinfo) {
303 struct addrinfo *res;
306 for (res = addrinfo; res; res = res->ai_next) {
307 s = bindtoaddr(srctcpres->addrinfo, res->ai_family, 1, 1);
309 debug(DBG_WARN, "connecttoserver: socket failed");
312 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
314 debug(DBG_WARN, "connecttoserver: connect failed");
321 /* returns 1 if the len first bits are equal, else 0 */
322 int prefixmatch(void *a1, void *a2, uint8_t len) {
323 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
325 if (l && memcmp(a1, a2, l))
330 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
333 /* returns the config with matching address, or NULL */
334 /* if conf argument is not NULL, we only check that one */
335 struct clsrvconf *find_conf(char type, struct sockaddr *addr, struct list *confs, struct clsrvconf *conf) {
336 struct sockaddr_in6 *sa6 = NULL;
337 struct in_addr *a4 = NULL;
338 struct addrinfo *res;
339 struct list_node *entry;
341 if (addr->sa_family == AF_INET6) {
342 sa6 = (struct sockaddr_in6 *)addr;
343 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
344 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
348 a4 = &((struct sockaddr_in *)addr)->sin_addr;
351 if (conf->type == type) {
352 if (conf->prefixlen == 255) {
353 for (res = conf->addrinfo; res; res = res->ai_next)
354 if ((a4 && res->ai_family == AF_INET &&
355 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
356 (sa6 && res->ai_family == AF_INET6 &&
357 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
360 res = conf->addrinfo;
362 ((a4 && res->ai_family == AF_INET &&
363 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
364 (sa6 && res->ai_family == AF_INET6 &&
365 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
372 for (entry = list_first(confs); entry; entry = list_next(entry)) {
373 conf = (struct clsrvconf *)entry->data;
374 if (conf->type == type) {
375 if (conf->prefixlen == 255) {
376 for (res = conf->addrinfo; res; res = res->ai_next)
377 if ((a4 && res->ai_family == AF_INET &&
378 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
379 (sa6 && res->ai_family == AF_INET6 &&
380 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
383 res = conf->addrinfo;
385 ((a4 && res->ai_family == AF_INET &&
386 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
387 (sa6 && res->ai_family == AF_INET6 &&
388 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
396 struct replyq *newreplyq() {
397 struct replyq *replyq;
399 replyq = malloc(sizeof(struct replyq));
401 debugx(1, DBG_ERR, "malloc failed");
402 replyq->replies = list_create();
403 if (!replyq->replies)
404 debugx(1, DBG_ERR, "malloc failed");
405 pthread_mutex_init(&replyq->mutex, NULL);
406 pthread_cond_init(&replyq->cond, NULL);
410 struct client *addclient(struct clsrvconf *conf) {
411 struct client *new = malloc(sizeof(struct client));
414 debug(DBG_ERR, "malloc failed");
417 if (!conf->clients) {
418 conf->clients = list_create();
419 if (!conf->clients) {
420 debug(DBG_ERR, "malloc failed");
425 memset(new, 0, sizeof(struct client));
427 new->replyq = conf->type == 'T' ? newreplyq() : udp_server_replyq;
429 list_push(conf->clients, new);
433 void removeclient(struct client *client) {
434 if (!client || !client->conf->clients)
437 list_removedata(client->conf->clients, client);
441 void addserver(struct clsrvconf *conf) {
443 debugx(1, DBG_ERR, "addserver: currently works with just one server per conf");
445 conf->servers = malloc(sizeof(struct server));
447 debugx(1, DBG_ERR, "malloc failed");
448 memset(conf->servers, 0, sizeof(struct server));
449 conf->servers->conf = conf;
451 if (conf->type == 'U') {
453 srcudpres = resolve_hostport('U', options.sourceudp, NULL);
454 switch (conf->addrinfo->ai_family) {
456 if (udp_client4_sock < 0) {
457 udp_client4_sock = bindtoaddr(srcudpres->addrinfo, AF_INET, 0, 1);
458 if (udp_client4_sock < 0)
459 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
461 conf->servers->sock = udp_client4_sock;
464 if (udp_client6_sock < 0) {
465 udp_client6_sock = bindtoaddr(srcudpres->addrinfo, AF_INET6, 0, 1);
466 if (udp_client6_sock < 0)
467 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
469 conf->servers->sock = udp_client6_sock;
472 debugx(1, DBG_ERR, "addserver: unsupported address family");
477 srctcpres = resolve_hostport('T', options.sourcetcp, NULL);
478 conf->servers->sock = -1;
481 pthread_mutex_init(&conf->servers->lock, NULL);
482 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
483 if (!conf->servers->requests)
484 debugx(1, DBG_ERR, "malloc failed");
485 conf->servers->newrq = 0;
486 pthread_mutex_init(&conf->servers->newrq_mutex, NULL);
487 pthread_cond_init(&conf->servers->newrq_cond, NULL);
490 /* exactly one of client and server must be non-NULL */
491 /* should probably take peer list (client(s) or server(s)) as argument instead */
492 /* if *peer == NULL we return who we received from, else require it to be from peer */
493 /* return from in sa if not NULL */
494 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
496 unsigned char buf[65536], *rad;
497 struct sockaddr_storage from;
498 socklen_t fromlen = sizeof(from);
500 struct list_node *node;
503 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
505 debug(DBG_WARN, "radudpget: recv failed");
508 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
511 debug(DBG_WARN, "radudpget: packet too small");
517 debug(DBG_WARN, "radudpget: length too small");
522 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
526 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
530 p = find_conf('U', (struct sockaddr *)&from, NULL, (*client)->conf);
532 p = find_conf('U', (struct sockaddr *)&from, clconfs, NULL);
535 p = find_conf('U', (struct sockaddr *)&from, NULL, (*server)->conf);
537 p = find_conf('U', (struct sockaddr *)&from, srvconfs, NULL);
540 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer, ignoring");
546 debug(DBG_ERR, "radudpget: malloc failed");
550 if (client && !*client) {
551 node = list_first(p->clients);
552 *client = node ? (struct client *)node->data : addclient(p);
557 } else if (server && !*server)
558 *server = p->servers;
562 memcpy(rad, buf, len);
568 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
569 int loc, i, l, n, r = 0;
572 STACK_OF(GENERAL_NAME) *alt;
575 debug(DBG_DBG, "subjectaltnameaddr");
577 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
581 ex = X509_get_ext(cert, loc);
582 alt = X509V3_EXT_d2i(ex);
586 n = sk_GENERAL_NAME_num(alt);
587 for (i = 0; i < n; i++) {
588 gn = sk_GENERAL_NAME_value(alt, i);
589 if (gn->type != GEN_IPADD)
592 v = (char *)ASN1_STRING_data(gn->d.ia5);
593 l = ASN1_STRING_length(gn->d.ia5);
594 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
595 && !memcmp(v, &addr, l)) {
600 GENERAL_NAMES_free(alt);
604 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
605 int loc, i, l, n, r = 0;
608 STACK_OF(GENERAL_NAME) *alt;
611 debug(DBG_DBG, "subjectaltnameregexp");
613 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
617 ex = X509_get_ext(cert, loc);
618 alt = X509V3_EXT_d2i(ex);
622 n = sk_GENERAL_NAME_num(alt);
623 for (i = 0; i < n; i++) {
624 gn = sk_GENERAL_NAME_value(alt, i);
625 if (gn->type != type)
628 v = (char *)ASN1_STRING_data(gn->d.ia5);
629 l = ASN1_STRING_length(gn->d.ia5);
633 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
636 if (memcmp(v, exact, l))
639 s = stringcopy((char *)v, l);
641 debug(DBG_ERR, "malloc failed");
644 if (regexec(regex, s, 0, NULL, 0)) {
653 GENERAL_NAMES_free(alt);
657 int tlsverifycert(SSL *ssl, struct clsrvconf *conf) {
664 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
666 struct in6_addr addr;
668 if (SSL_get_verify_result(ssl) != X509_V_OK) {
669 debug(DBG_ERR, "tlsverifycert: basic validation failed");
670 while ((error = ERR_get_error()))
671 debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
675 cert = SSL_get_peer_certificate(ssl);
677 debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
681 if (conf->prefixlen == 255) {
682 if (inet_pton(AF_INET, conf->host, &addr))
684 else if (inet_pton(AF_INET6, conf->host, &addr))
687 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
691 debug(DBG_DBG, "tlsverifycert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
694 debug(DBG_DBG, "tlsverifycert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
696 nm = X509_get_subject_name(cert);
699 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
702 e = X509_NAME_get_entry(nm, loc);
703 s = X509_NAME_ENTRY_get_data(e);
704 v = (char *) ASN1_STRING_data(s);
705 l = ASN1_STRING_length(s);
709 printfchars(NULL, "cn", NULL, v, l);
711 if (l == strlen(conf->host) && !strncasecmp(conf->host, v, l)) {
713 debug(DBG_DBG, "tlsverifycert: Found cn matching host %s", conf->host);
719 debug(DBG_ERR, "tlsverifycert: cn not matching host %s", conf->host);
724 if (conf->certuriregex) {
725 r = subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex);
727 debug(DBG_DBG, "tlsverifycert: subjectaltname URI not matching regex");
731 debug(DBG_DBG, "tlsverifycert: subjectaltname URI matching regex");
737 void tlsconnect(struct server *server, struct timeval *when, char *text) {
741 debug(DBG_DBG, "tlsconnect called from %s", text);
742 pthread_mutex_lock(&server->lock);
743 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
744 /* already reconnected, nothing to do */
745 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
746 pthread_mutex_unlock(&server->lock);
750 debug(DBG_DBG, "tlsconnect %s", text);
753 gettimeofday(&now, NULL);
754 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
755 if (server->connectionok) {
756 server->connectionok = 0;
758 } else if (elapsed < 5)
760 else if (elapsed < 300) {
761 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
763 } else if (elapsed < 100000) {
764 debug(DBG_INFO, "tlsconnect: sleeping %ds", 600);
767 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
768 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
769 if (server->sock >= 0)
771 if ((server->sock = connecttcp(server->conf->addrinfo)) < 0) {
772 debug(DBG_ERR, "tlsconnect: connecttcp failed");
776 SSL_free(server->ssl);
777 server->ssl = SSL_new(server->conf->ssl_ctx);
778 SSL_set_fd(server->ssl, server->sock);
779 if (SSL_connect(server->ssl) > 0 && tlsverifycert(server->ssl, server->conf))
782 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
783 gettimeofday(&server->lastconnecttry, NULL);
784 pthread_mutex_unlock(&server->lock);
787 unsigned char *radtlsget(SSL *ssl) {
789 unsigned char buf[4], *rad;
792 for (total = 0; total < 4; total += cnt) {
793 cnt = SSL_read(ssl, buf + total, 4 - total);
795 debug(DBG_ERR, "radtlsget: connection lost");
796 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
797 /* remote end sent close_notify, send one back */
807 debug(DBG_ERR, "radtlsget: malloc failed");
812 for (; total < len; total += cnt) {
813 cnt = SSL_read(ssl, rad + total, len - total);
815 debug(DBG_ERR, "radtlsget: connection lost");
816 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
817 /* remote end sent close_notify, send one back */
829 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
832 debug(DBG_DBG, "radtlsget: got %d bytes", total);
836 int clientradput(struct server *server, unsigned char *rad) {
840 struct timeval lastconnecttry;
841 struct clsrvconf *conf = server->conf;
844 if (conf->type == 'U') {
845 if (sendto(server->sock, rad, len, 0, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen) >= 0) {
846 debug(DBG_DBG, "clienradput: sent UDP of length %d to %s port %s", len, conf->host, conf->port);
849 debug(DBG_WARN, "clientradput: send failed");
853 lastconnecttry = server->lastconnecttry;
854 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
855 while ((error = ERR_get_error()))
856 debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
857 tlsconnect(server, &lastconnecttry, "clientradput");
858 lastconnecttry = server->lastconnecttry;
861 server->connectionok = 1;
862 debug(DBG_DBG, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
866 int radsign(unsigned char *rad, unsigned char *sec) {
867 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
868 static unsigned char first = 1;
869 static EVP_MD_CTX mdctx;
873 pthread_mutex_lock(&lock);
875 EVP_MD_CTX_init(&mdctx);
879 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
880 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
881 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
882 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
884 pthread_mutex_unlock(&lock);
888 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
889 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
890 static unsigned char first = 1;
891 static EVP_MD_CTX mdctx;
892 unsigned char hash[EVP_MAX_MD_SIZE];
896 pthread_mutex_lock(&lock);
898 EVP_MD_CTX_init(&mdctx);
904 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
905 EVP_DigestUpdate(&mdctx, rad, 4) &&
906 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
907 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
908 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
909 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
911 !memcmp(hash, rad + 4, 16));
912 pthread_mutex_unlock(&lock);
916 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
917 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
918 static unsigned char first = 1;
919 static HMAC_CTX hmacctx;
921 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
923 pthread_mutex_lock(&lock);
925 HMAC_CTX_init(&hmacctx);
929 memcpy(auth, authattr, 16);
930 memset(authattr, 0, 16);
932 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
933 HMAC_Update(&hmacctx, rad, RADLEN(rad));
934 HMAC_Final(&hmacctx, hash, &md_len);
935 memcpy(authattr, auth, 16);
937 debug(DBG_WARN, "message auth computation failed");
938 pthread_mutex_unlock(&lock);
942 if (memcmp(auth, hash, 16)) {
943 debug(DBG_WARN, "message authenticator, wrong value");
944 pthread_mutex_unlock(&lock);
948 pthread_mutex_unlock(&lock);
952 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
953 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
954 static unsigned char first = 1;
955 static HMAC_CTX hmacctx;
961 pthread_mutex_lock(&lock);
963 HMAC_CTX_init(&hmacctx);
967 memset(authattrval, 0, 16);
969 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
970 HMAC_Update(&hmacctx, rad, RADLEN(rad));
971 HMAC_Final(&hmacctx, authattrval, &md_len);
973 debug(DBG_WARN, "message auth computation failed");
974 pthread_mutex_unlock(&lock);
978 pthread_mutex_unlock(&lock);
982 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
984 if (ATTRTYPE(attrs) == type)
986 length -= ATTRLEN(attrs);
987 attrs += ATTRLEN(attrs);
992 void freerqdata(struct request *rq) {
993 if (rq->origusername)
994 free(rq->origusername);
999 void sendrq(struct server *to, struct request *rq) {
1003 pthread_mutex_lock(&to->newrq_mutex);
1004 /* might simplify if only try nextid, might be ok */
1005 for (i = to->nextid; i < MAX_REQUESTS; i++)
1006 if (!to->requests[i].buf)
1008 if (i == MAX_REQUESTS) {
1009 for (i = 0; i < to->nextid; i++)
1010 if (!to->requests[i].buf)
1012 if (i == to->nextid) {
1013 debug(DBG_WARN, "No room in queue, dropping request");
1015 pthread_mutex_unlock(&to->newrq_mutex);
1020 rq->buf[1] = (char)i;
1022 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1023 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1025 pthread_mutex_unlock(&to->newrq_mutex);
1029 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1030 to->requests[i] = *rq;
1035 debug(DBG_DBG, "signalling client writer");
1036 pthread_cond_signal(&to->newrq_cond);
1038 pthread_mutex_unlock(&to->newrq_mutex);
1041 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
1042 struct reply *reply;
1045 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1047 debug(DBG_WARN, "sendreply: failed to sign message");
1051 reply = malloc(sizeof(struct reply));
1054 debug(DBG_ERR, "sendreply: malloc failed");
1057 memset(reply, 0, sizeof(struct reply));
1060 reply->tosa = *tosa;
1062 pthread_mutex_lock(&to->replyq->mutex);
1064 first = list_first(to->replyq->replies) == NULL;
1066 if (!list_push(to->replyq->replies, reply)) {
1067 pthread_mutex_unlock(&to->replyq->mutex);
1070 debug(DBG_ERR, "sendreply: malloc failed");
1075 debug(DBG_DBG, "signalling server writer");
1076 pthread_cond_signal(&to->replyq->cond);
1078 pthread_mutex_unlock(&to->replyq->mutex);
1081 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1082 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1083 static unsigned char first = 1;
1084 static EVP_MD_CTX mdctx;
1085 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1086 unsigned int md_len;
1087 uint8_t i, offset = 0, out[128];
1089 pthread_mutex_lock(&lock);
1091 EVP_MD_CTX_init(&mdctx);
1097 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1098 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1099 !EVP_DigestUpdate(&mdctx, input, 16) ||
1100 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1102 pthread_mutex_unlock(&lock);
1105 for (i = 0; i < 16; i++)
1106 out[offset + i] = hash[i] ^ in[offset + i];
1107 input = out + offset - 16;
1112 memcpy(in, out, len);
1113 pthread_mutex_unlock(&lock);
1117 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1118 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1119 static unsigned char first = 1;
1120 static EVP_MD_CTX mdctx;
1121 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1122 unsigned int md_len;
1123 uint8_t i, offset = 0, out[128];
1125 pthread_mutex_lock(&lock);
1127 EVP_MD_CTX_init(&mdctx);
1133 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1134 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1135 !EVP_DigestUpdate(&mdctx, input, 16) ||
1136 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1138 pthread_mutex_unlock(&lock);
1141 for (i = 0; i < 16; i++)
1142 out[offset + i] = hash[i] ^ in[offset + i];
1143 input = in + offset;
1148 memcpy(in, out, len);
1149 pthread_mutex_unlock(&lock);
1153 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1154 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1155 static unsigned char first = 1;
1156 static EVP_MD_CTX mdctx;
1157 unsigned char hash[EVP_MAX_MD_SIZE];
1158 unsigned int md_len;
1161 pthread_mutex_lock(&lock);
1163 EVP_MD_CTX_init(&mdctx);
1168 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1169 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1170 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1173 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1174 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1175 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1176 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1177 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1178 pthread_mutex_unlock(&lock);
1183 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1186 for (i = 0; i < 16; i++)
1189 for (offset = 16; offset < len; offset += 16) {
1191 printf("text + offset - 16 c(%d): ", offset / 16);
1192 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1194 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1195 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1196 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1197 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1199 pthread_mutex_unlock(&lock);
1203 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1206 for (i = 0; i < 16; i++)
1207 text[offset + i] ^= hash[i];
1211 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1214 pthread_mutex_unlock(&lock);
1218 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1219 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1220 static unsigned char first = 1;
1221 static EVP_MD_CTX mdctx;
1222 unsigned char hash[EVP_MAX_MD_SIZE];
1223 unsigned int md_len;
1227 pthread_mutex_lock(&lock);
1229 EVP_MD_CTX_init(&mdctx);
1234 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1235 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1236 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1239 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1240 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1241 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1242 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1243 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1244 pthread_mutex_unlock(&lock);
1249 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1252 for (i = 0; i < 16; i++)
1253 plain[i] = text[i] ^ hash[i];
1255 for (offset = 16; offset < len; offset += 16) {
1257 printf("text + offset - 16 c(%d): ", offset / 16);
1258 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1260 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1261 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1262 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1263 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1265 pthread_mutex_unlock(&lock);
1269 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1272 for (i = 0; i < 16; i++)
1273 plain[offset + i] = text[offset + i] ^ hash[i];
1276 memcpy(text, plain, len);
1278 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1281 pthread_mutex_unlock(&lock);
1285 struct realm *id2realm(char *id, uint8_t len) {
1286 struct list_node *entry;
1287 struct realm *realm;
1289 for (entry = list_first(realms); entry; entry = list_next(entry)) {
1290 realm = (struct realm *)entry->data;
1291 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1292 debug(DBG_DBG, "found matching realm: %s", realm->name);
1299 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
1302 pthread_mutex_lock(&to->newrq_mutex);
1303 for (i = 0; i < MAX_REQUESTS; i++)
1304 if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
1306 pthread_mutex_unlock(&to->newrq_mutex);
1308 return i < MAX_REQUESTS;
1311 int attrvalidate(unsigned char *attrs, int length) {
1312 while (length > 1) {
1313 if (ATTRLEN(attrs) < 2) {
1314 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1317 length -= ATTRLEN(attrs);
1319 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1322 attrs += ATTRLEN(attrs);
1325 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1329 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1330 if (len < 16 || len > 128 || len % 16) {
1331 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1335 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1336 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1340 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1342 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1343 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1349 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1352 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1353 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1356 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1357 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1363 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1364 char *oldsecret, char *newsecret) {
1365 unsigned char *attr;
1367 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1368 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1369 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1375 /* returns a pointer to the resized attribute value */
1376 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1377 uint8_t *attrs, *attr, vallen;
1381 len = RADLEN(*buf) - 20;
1384 attr = attrget(attrs, len, type);
1388 vallen = ATTRVALLEN(attr);
1389 if (vallen == newvallen)
1392 len += newvallen - vallen;
1393 if (newvallen > vallen) {
1394 new = realloc(*buf, len);
1396 debug(DBG_ERR, "resizeattr: malloc failed");
1405 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1406 attr[1] = newvallen + 2;
1407 ((uint16_t *)*buf)[1] = htons(len + 20);
1411 int rewriteusername(struct request *rq, char *in) {
1412 size_t nmatch = 10, reslen = 0, start = 0;
1413 regmatch_t pmatch[10], *pfield;
1415 unsigned char *result;
1416 char *out = rq->from->conf->rewriteattrreplacement;
1418 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1419 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1423 rq->origusername = stringcopy(in, 0);
1424 if (!rq->origusername)
1427 for (i = start; out[i]; i++) {
1428 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1429 pfield = &pmatch[out[i + 1] - '0'];
1430 if (pfield->rm_so >= 0) {
1431 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1437 reslen += i - start;
1439 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1445 for (i = start; out[i]; i++) {
1446 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1447 pfield = &pmatch[out[i + 1] - '0'];
1448 if (pfield->rm_so >= 0) {
1449 memcpy(result + reslen, out + start, i - start);
1450 reslen += i - start;
1451 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1452 reslen += pfield->rm_eo - pfield->rm_so;
1459 memcpy(result + reslen, out + start, i - start);
1460 reslen += i - start;
1461 memcpy(in, result, reslen);
1466 void acclog(unsigned char *attrs, int length, char *host) {
1467 unsigned char *attr;
1470 attr = attrget(attrs, length, RAD_Attr_User_Name);
1472 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1475 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1476 username[ATTRVALLEN(attr)] = '\0';
1477 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1480 void respondaccounting(struct request *rq) {
1481 unsigned char *resp;
1485 debug(DBG_ERR, "respondstatusserver: malloc failed");
1488 memcpy(resp, rq->buf, 20);
1489 resp[0] = RAD_Accounting_Response;
1492 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1493 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1496 void respondstatusserver(struct request *rq) {
1497 unsigned char *resp;
1501 debug(DBG_ERR, "respondstatusserver: malloc failed");
1504 memcpy(resp, rq->buf, 20);
1505 resp[0] = RAD_Access_Accept;
1508 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1509 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1512 void respondreject(struct request *rq, char *message) {
1513 unsigned char *resp;
1516 if (message && *message)
1517 len += 2 + strlen(message);
1521 debug(DBG_ERR, "respondreject: malloc failed");
1524 memcpy(resp, rq->buf, 20);
1525 resp[0] = RAD_Access_Reject;
1526 *(uint16_t *)(resp + 2) = htons(len);
1527 if (message && *message) {
1528 resp[20] = RAD_Attr_Reply_Message;
1529 resp[21] = len - 20;
1530 memcpy(resp + 22, message, len - 22);
1532 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1535 struct server *realm2server(struct realm *realm) {
1536 struct list_node *entry;
1537 struct server *server, *best = NULL;
1539 for (entry = list_first(realm->srvconfs); entry; entry = list_next(entry)) {
1540 server = ((struct clsrvconf *)entry->data)->servers;
1541 if (!server->connectionok)
1543 if (!server->loststatsrv)
1549 if (server->loststatsrv < best->loststatsrv)
1555 void radsrv(struct request *rq) {
1556 uint8_t code, id, *auth, *attrs, *attr;
1558 struct server *to = NULL;
1560 unsigned char newauth[16];
1561 struct realm *realm = NULL;
1563 code = *(uint8_t *)rq->buf;
1564 id = *(uint8_t *)(rq->buf + 1);
1565 len = RADLEN(rq->buf);
1566 auth = (uint8_t *)(rq->buf + 4);
1568 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1570 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1571 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1577 attrs = rq->buf + 20;
1579 if (!attrvalidate(attrs, len)) {
1580 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1585 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1586 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
1587 debug(DBG_WARN, "radsrv: message authentication failed");
1592 if (code != RAD_Access_Request) {
1594 case RAD_Accounting_Request:
1595 acclog(attrs, len, rq->from->conf->host);
1596 respondaccounting(rq);
1598 case RAD_Status_Server:
1599 respondstatusserver(rq);
1606 /* code == RAD_Access_Request */
1607 attr = attrget(attrs, len, RAD_Attr_User_Name);
1609 debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1613 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1614 username[ATTRVALLEN(attr)] = '\0';
1616 if (rq->from->conf->rewriteattrregex) {
1617 if (!rewriteusername(rq, username)) {
1618 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1622 len = RADLEN(rq->buf) - 20;
1623 auth = (uint8_t *)(rq->buf + 4);
1624 attrs = rq->buf + 20;
1627 if (rq->origusername)
1628 debug(DBG_DBG, "Access Request with username: %s (originally %s)", username, rq->origusername);
1630 debug(DBG_DBG, "Access Request with username: %s", username);
1632 realm = id2realm(username, strlen(username));
1634 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1639 to = realm2server(realm);
1640 if (to && rqinqueue(to, rq->from, id)) {
1641 debug(DBG_INFO, "radsrv: already got request from host %s with id %d, ignoring", rq->from->conf->host, id);
1647 if (realm->message) {
1648 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, username);
1649 respondreject(rq, realm->message);
1655 if (!RAND_bytes(newauth, 16)) {
1656 debug(DBG_WARN, "radsrv: failed to generate random auth");
1662 printfchars(NULL, "auth", "%02x ", auth, 16);
1665 attr = attrget(attrs, len, RAD_Attr_User_Password);
1667 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1668 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1674 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1676 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1677 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1684 memcpy(rq->origauth, auth, 16);
1685 memcpy(auth, newauth, 16);
1689 int replyh(struct server *server, unsigned char *buf) {
1690 struct client *from;
1693 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
1694 struct sockaddr_storage fromsa;
1697 server->connectionok = 1;
1698 server->loststatsrv = 0;
1700 i = buf[1]; /* i is the id */
1703 case RAD_Access_Accept:
1704 debug(DBG_DBG, "got Access Accept with id %d", i);
1706 case RAD_Access_Reject:
1707 debug(DBG_DBG, "got Access Reject with id %d", i);
1709 case RAD_Access_Challenge:
1710 debug(DBG_DBG, "got Access Challenge with id %d", i);
1713 debug(DBG_INFO, "replyh: discarding, only accept access accept, access reject and access challenge messages");
1717 rq = server->requests + i;
1719 pthread_mutex_lock(&server->newrq_mutex);
1720 if (!rq->buf || !rq->tries) {
1721 pthread_mutex_unlock(&server->newrq_mutex);
1722 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
1727 pthread_mutex_unlock(&server->newrq_mutex);
1728 debug(DBG_INFO, "replyh: already received, ignoring reply");
1732 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
1733 pthread_mutex_unlock(&server->newrq_mutex);
1734 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
1739 len = RADLEN(buf) - 20;
1742 if (!attrvalidate(attrs, len)) {
1743 pthread_mutex_unlock(&server->newrq_mutex);
1744 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
1748 /* Message Authenticator */
1749 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1751 if (ATTRVALLEN(messageauth) != 16) {
1752 pthread_mutex_unlock(&server->newrq_mutex);
1753 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
1756 memcpy(tmp, buf + 4, 16);
1757 memcpy(buf + 4, rq->buf + 4, 16);
1758 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
1759 pthread_mutex_unlock(&server->newrq_mutex);
1760 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
1763 memcpy(buf + 4, tmp, 16);
1764 debug(DBG_DBG, "replyh: message auth ok");
1767 if (*rq->buf == RAD_Status_Server) {
1769 pthread_mutex_unlock(&server->newrq_mutex);
1770 debug(DBG_INFO, "replyh: got status server response from %s", server->conf->host);
1775 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1776 if (ATTRVALLEN(attr) <= 4)
1779 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
1782 sublen = ATTRVALLEN(attr) - 4;
1783 subattrs = ATTRVAL(attr) + 4;
1784 if (!attrvalidate(subattrs, sublen) ||
1785 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1786 rq, server->conf->secret, from->conf->secret) ||
1787 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1788 rq, server->conf->secret, from->conf->secret))
1792 pthread_mutex_unlock(&server->newrq_mutex);
1793 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1797 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject) {
1798 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
1799 /* we know the attribute exists */
1800 memcpy(tmp, ATTRVAL(attr), ATTRVALLEN(attr));
1801 tmp[ATTRVALLEN(attr)] = '\0';
1803 case RAD_Access_Accept:
1804 if (rq->origusername)
1805 debug(DBG_INFO, "Access Accept for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1807 debug(DBG_INFO, "Access Accept for %s from %s", tmp, server->conf->host);
1809 case RAD_Access_Reject:
1810 if (rq->origusername)
1811 debug(DBG_INFO, "Access Reject for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1813 debug(DBG_INFO, "Access Reject for %s from %s", tmp, server->conf->host);
1818 buf[1] = (char)rq->origid;
1819 memcpy(buf + 4, rq->origauth, 16);
1821 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1824 if (rq->origusername) {
1825 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
1827 pthread_mutex_unlock(&server->newrq_mutex);
1828 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1831 memcpy(username, rq->origusername, strlen(rq->origusername));
1832 len = RADLEN(buf) - 20;
1835 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1839 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
1840 pthread_mutex_unlock(&server->newrq_mutex);
1841 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
1844 debug(DBG_DBG, "replyh: computed messageauthattr");
1847 if (from->conf->type == 'U')
1848 fromsa = rq->fromsa;
1849 /* once we set received = 1, rq may be reused */
1851 pthread_mutex_unlock(&server->newrq_mutex);
1853 debug(DBG_DBG, "replyh: giving packet back to where it came from");
1854 sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
1858 void *udpclientrd(void *arg) {
1859 struct server *server;
1861 int *s = (int *)arg;
1865 buf = radudpget(*s, NULL, &server, NULL);
1866 if (!replyh(server, buf))
1871 void *tlsclientrd(void *arg) {
1872 struct server *server = (struct server *)arg;
1874 struct timeval lastconnecttry;
1877 /* yes, lastconnecttry is really necessary */
1878 lastconnecttry = server->lastconnecttry;
1879 buf = radtlsget(server->ssl);
1881 tlsconnect(server, &lastconnecttry, "clientrd");
1885 if (!replyh(server, buf))
1890 void *clientwr(void *arg) {
1891 struct server *server = (struct server *)arg;
1893 pthread_t tlsclientrdth;
1896 struct timeval now, lastsend;
1897 struct timespec timeout;
1898 struct request statsrvrq;
1899 unsigned char statsrvbuf[38];
1901 memset(&timeout, 0, sizeof(struct timespec));
1903 if (server->conf->statusserver) {
1904 memset(&statsrvrq, 0, sizeof(struct request));
1905 memset(statsrvbuf, 0, sizeof(statsrvbuf));
1906 statsrvbuf[0] = RAD_Status_Server;
1908 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
1909 statsrvbuf[21] = 18;
1910 gettimeofday(&lastsend, NULL);
1913 if (server->conf->type == 'U') {
1914 server->connectionok = 1;
1916 tlsconnect(server, NULL, "new client");
1917 server->connectionok = 1;
1918 if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server))
1919 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
1923 pthread_mutex_lock(&server->newrq_mutex);
1924 if (!server->newrq) {
1925 gettimeofday(&now, NULL);
1926 if (server->conf->statusserver) {
1927 /* random 0-7 seconds */
1928 RAND_bytes(&rnd, 1);
1930 if (!timeout.tv_sec || timeout.tv_sec - now.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
1931 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
1933 if (timeout.tv_sec) {
1934 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1935 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1938 debug(DBG_DBG, "clientwr: waiting for new request");
1939 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1942 if (server->newrq) {
1943 debug(DBG_DBG, "clientwr: got new request");
1946 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1947 pthread_mutex_unlock(&server->newrq_mutex);
1949 for (i = 0; i < MAX_REQUESTS; i++) {
1950 pthread_mutex_lock(&server->newrq_mutex);
1951 while (i < MAX_REQUESTS && !server->requests[i].buf)
1953 if (i == MAX_REQUESTS) {
1954 pthread_mutex_unlock(&server->newrq_mutex);
1957 rq = server->requests + i;
1960 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
1962 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
1964 /* setting this to NULL means that it can be reused */
1967 pthread_mutex_unlock(&server->newrq_mutex);
1971 gettimeofday(&now, NULL);
1972 if (now.tv_sec < rq->expiry.tv_sec) {
1973 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1974 timeout.tv_sec = rq->expiry.tv_sec;
1975 pthread_mutex_unlock(&server->newrq_mutex);
1979 if (rq->tries == (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
1980 ? 1 : REQUEST_RETRIES)) {
1981 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1982 if (*rq->buf == RAD_Status_Server) {
1983 debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->conf->host);
1984 if (server->loststatsrv < 255)
1985 server->loststatsrv++;
1988 /* setting this to NULL means that it can be reused */
1990 pthread_mutex_unlock(&server->newrq_mutex);
1993 pthread_mutex_unlock(&server->newrq_mutex);
1995 rq->expiry.tv_sec = now.tv_sec +
1996 (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
1997 ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
1998 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1999 timeout.tv_sec = rq->expiry.tv_sec;
2001 clientradput(server, server->requests[i].buf);
2002 gettimeofday(&lastsend, NULL);
2004 if (server->conf->statusserver) {
2005 gettimeofday(&now, NULL);
2006 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
2007 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2008 debug(DBG_WARN, "clientwr: failed to generate random auth");
2011 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2012 if (!statsrvrq.buf) {
2013 debug(DBG_ERR, "clientwr: malloc failed");
2016 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2017 debug(DBG_DBG, "clientwr: sending status server to %s", server->conf->host);
2018 lastsend.tv_sec = now.tv_sec;
2019 sendrq(server, &statsrvrq);
2025 void *udpserverwr(void *arg) {
2026 struct replyq *replyq = udp_server_replyq;
2027 struct reply *reply;
2030 pthread_mutex_lock(&replyq->mutex);
2031 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2032 debug(DBG_DBG, "udp server writer, waiting for signal");
2033 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2034 debug(DBG_DBG, "udp server writer, got signal");
2036 pthread_mutex_unlock(&replyq->mutex);
2038 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
2039 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2040 debug(DBG_WARN, "sendudp: send failed");
2046 void *udpserverrd(void *arg) {
2048 pthread_t udpserverwrth;
2049 struct clsrvconf *listenres;
2051 listenres = resolve_hostport('U', options.listenudp, DEFAULT_UDP_PORT);
2052 if ((udp_server_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2053 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2055 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
2056 listenres->host ? listenres->host : "*", listenres->port);
2059 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
2060 debugx(1, DBG_ERR, "pthread_create failed");
2063 memset(&rq, 0, sizeof(struct request));
2064 rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
2069 void *udpaccserverrd(void *arg) {
2071 struct clsrvconf *listenres;
2073 listenres = resolve_hostport('U', options.listenaccudp, DEFAULT_UDP_PORT);
2074 if ((udp_accserver_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2075 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2077 debug(DBG_WARN, "udpaccserverrd: listening for UDP on %s:%s",
2078 listenres->host ? listenres->host : "*", listenres->port);
2082 memset(&rq, 0, sizeof(struct request));
2083 rq.buf = radudpget(udp_accserver_sock, &rq.from, NULL, &rq.fromsa);
2084 if (*(uint8_t *)rq.buf == RAD_Accounting_Request) {
2088 debug(DBG_INFO, "udpaccserverrd: got something other than accounting-request, ignoring");
2093 void *tlsserverwr(void *arg) {
2095 unsigned long error;
2096 struct client *client = (struct client *)arg;
2097 struct replyq *replyq;
2098 struct reply *reply;
2100 debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
2101 replyq = client->replyq;
2103 pthread_mutex_lock(&replyq->mutex);
2104 while (!list_first(replyq->replies)) {
2106 debug(DBG_DBG, "tls server writer, waiting for signal");
2107 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2108 debug(DBG_DBG, "tls server writer, got signal");
2111 /* ssl might have changed while waiting */
2112 pthread_mutex_unlock(&replyq->mutex);
2113 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2117 reply = (struct reply *)list_shift(replyq->replies);
2118 pthread_mutex_unlock(&replyq->mutex);
2119 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2121 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
2122 cnt, RADLEN(reply->buf));
2124 while ((error = ERR_get_error()))
2125 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2131 void *tlsserverrd(void *arg) {
2133 unsigned long error;
2135 struct client *client = (struct client *)arg;
2136 pthread_t tlsserverwrth;
2139 debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2142 if (SSL_accept(ssl) <= 0) {
2143 while ((error = ERR_get_error()))
2144 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2145 debug(DBG_ERR, "SSL_accept failed");
2148 if (tlsverifycert(client->ssl, client->conf)) {
2149 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2150 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2154 memset(&rq, 0, sizeof(struct request));
2155 rq.buf = radtlsget(client->ssl);
2158 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2162 debug(DBG_ERR, "tlsserverrd: connection lost");
2163 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2165 pthread_mutex_lock(&client->replyq->mutex);
2166 pthread_cond_signal(&client->replyq->cond);
2167 pthread_mutex_unlock(&client->replyq->mutex);
2168 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2169 pthread_join(tlsserverwrth, NULL);
2173 s = SSL_get_fd(ssl);
2175 shutdown(s, SHUT_RDWR);
2177 debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->conf->host);
2178 removeclient(client);
2183 pthread_t tlsserverth;
2185 struct sockaddr_storage from;
2186 size_t fromlen = sizeof(from);
2187 struct clsrvconf *conf;
2188 struct client *client;
2189 struct clsrvconf *listenres;
2191 listenres = resolve_hostport('T', options.listentcp, DEFAULT_TLS_PORT);
2192 if ((s = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2193 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
2196 debug(DBG_WARN, "listening for incoming TCP on %s:%s", listenres->host ? listenres->host : "*", listenres->port);
2200 snew = accept(s, (struct sockaddr *)&from, &fromlen);
2202 debug(DBG_WARN, "accept failed");
2205 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2207 conf = find_conf('T', (struct sockaddr *)&from, clconfs, NULL);
2209 debug(DBG_WARN, "ignoring request, not a known TLS client");
2210 shutdown(snew, SHUT_RDWR);
2215 client = addclient(conf);
2218 debug(DBG_WARN, "Failed to create new client instance");
2219 shutdown(snew, SHUT_RDWR);
2223 client->ssl = SSL_new(client->conf->ssl_ctx);
2224 SSL_set_fd(client->ssl, snew);
2225 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
2226 debug(DBG_ERR, "tlslistener: pthread_create failed");
2227 SSL_free(client->ssl);
2228 removeclient(client);
2229 shutdown(snew, SHUT_RDWR);
2233 pthread_detach(tlsserverth);
2238 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
2241 STACK_OF(X509_NAME) *calist;
2243 unsigned long error;
2245 if (!certfile || !certkeyfile)
2246 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2248 if (!cacertfile && !cacertpath)
2249 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2252 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2253 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2254 for (i = 0; i < CRYPTO_num_locks(); i++) {
2255 ssl_lock_count[i] = 0;
2256 pthread_mutex_init(&ssl_locks[i], NULL);
2258 CRYPTO_set_id_callback(ssl_thread_id);
2259 CRYPTO_set_locking_callback(ssl_locking_callback);
2261 SSL_load_error_strings();
2264 while (!RAND_status()) {
2265 time_t t = time(NULL);
2266 pid_t pid = getpid();
2267 RAND_seed((unsigned char *)&t, sizeof(time_t));
2268 RAND_seed((unsigned char *)&pid, sizeof(pid));
2271 ctx = SSL_CTX_new(TLSv1_method());
2273 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2274 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2276 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2277 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2278 !SSL_CTX_check_private_key(ctx) ||
2279 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2280 while ((error = ERR_get_error()))
2281 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2282 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2285 calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
2286 if (!cacertfile || calist) {
2289 calist = sk_X509_NAME_new_null();
2290 if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
2291 sk_X509_NAME_free(calist);
2297 while ((error = ERR_get_error()))
2298 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2299 debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
2301 SSL_CTX_set_client_CA_list(ctx, calist);
2303 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2304 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2306 new = malloc(sizeof(struct tls));
2307 if (!new || !list_push(tlsconfs, new))
2308 debugx(1, DBG_ERR, "malloc failed");
2310 memset(new, 0, sizeof(struct tls));
2311 new->name = stringcopy(value, 0);
2313 debugx(1, DBG_ERR, "malloc failed");
2316 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2320 struct list_node *entry;
2323 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2324 t = (struct tls *)entry->data;
2328 SSL_CTX_free(t->ctx);
2330 list_destroy(tlsconfs);
2334 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2335 struct list_node *entry;
2336 struct tls *t, *t1 = NULL, *t2 = NULL;
2338 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2339 t = (struct tls *)entry->data;
2340 if (!strcasecmp(t->name, alt1)) {
2344 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2355 void addrealm(char *value, char **servers, char *message) {
2357 struct realm *realm;
2358 char *s, *regex = NULL;
2359 struct list_node *entry;
2360 struct clsrvconf *conf;
2362 if (*value == '/') {
2363 /* regexp, remove optional trailing / if present */
2364 if (value[strlen(value) - 1] == '/')
2365 value[strlen(value) - 1] = '\0';
2367 /* not a regexp, let us make it one */
2368 if (*value == '*' && !value[1])
2369 regex = stringcopy(".*", 0);
2371 for (n = 0, s = value; *s;)
2374 regex = malloc(strlen(value) + n + 3);
2377 for (n = 1, s = value; *s; s++) {
2387 debugx(1, DBG_ERR, "malloc failed");
2388 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2391 realm = malloc(sizeof(struct realm));
2393 debugx(1, DBG_ERR, "malloc failed");
2395 memset(realm, 0, sizeof(struct realm));
2396 realm->name = stringcopy(value, 0);
2398 debugx(1, DBG_ERR, "malloc failed");
2399 if (message && strlen(message) > 253)
2400 debugx(1, DBG_ERR, "ReplyMessage can be at most 253 bytes");
2401 realm->message = message;
2403 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB))
2404 debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2408 if (servers && *servers) {
2409 realm->srvconfs = list_create();
2410 if (!realm->srvconfs)
2411 debugx(1, DBG_ERR, "malloc failed");
2412 for (n = 0; servers[n]; n++) {
2413 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2414 conf = (struct clsrvconf *)entry->data;
2415 if (!strcasecmp(servers[n], conf->name))
2419 debugx(1, DBG_ERR, "addrealm failed, no server %s", servers[n]);
2420 if (!list_push(realm->srvconfs, conf))
2421 debugx(1, DBG_ERR, "malloc failed");
2422 debug(DBG_DBG, "addrealm: added server %s for realm %s", conf->name, value);
2425 realm->srvconfs = NULL;
2427 if (!list_push(realms, realm))
2428 debugx(1, DBG_ERR, "malloc failed");
2429 debug(DBG_DBG, "addrealm: added realm %s", value);
2432 FILE *openconfigfile(const char *filename) {
2434 char pathname[100], *base = NULL;
2436 f = fopen(filename, "r");
2438 debug(DBG_DBG, "reading config file %s", filename);
2442 if (strlen(filename) + 1 <= sizeof(pathname)) {
2443 /* basename() might modify the string */
2444 strcpy(pathname, filename);
2445 base = basename(pathname);
2446 f = fopen(base, "r");
2450 debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
2452 debug(DBG_DBG, "reading config file %s", base);
2456 /* returns NULL on error, where to continue parsing if token and ok. E.g. "" will return token with empty string */
2457 char *strtokenquote(char *s, char **token, char *del, char *quote, char *comment) {
2458 char *t = s, *q, *r;
2460 if (!t || !token || !del)
2462 while (*t && strchr(del, *t))
2464 if (!*t || (comment && strchr(comment, *t))) {
2466 return t + 1; /* needs to be non-NULL, but value doesn't matter */
2468 if (quote && (q = strchr(quote, *t))) {
2471 while (*t && *t != *q)
2473 if (!*t || (t[1] && !strchr(del, t[1])))
2481 while (*t && !strchr(del, *t))
2487 /* Parses config with following syntax:
2490 * option-name = value
2492 * option-name value {
2493 * option-name [=] value
2497 void getgeneralconfig(FILE *f, char *block, ...) {
2500 /* initialise lots of stuff to avoid stupid compiler warnings */
2501 char *tokens[3], *s, *opt = NULL, *val = NULL, *word, *optval, **str = NULL, ***mstr = NULL;
2502 int type = 0, tcount, conftype = 0, n;
2503 void (*cbk)(FILE *, char *, char *, char *) = NULL;
2505 while (fgets(line, 1024, f)) {
2507 for (tcount = 0; tcount < 3; tcount++) {
2508 s = strtokenquote(s, &tokens[tcount], " \t\r\n", "\"'", tcount ? NULL : "#");
2510 debugx(1, DBG_ERR, "Syntax error in line starting with: %s", line);
2511 if (!tokens[tcount])
2514 if (!tcount || **tokens == '#')
2517 if (**tokens == '}') {
2520 debugx(1, DBG_ERR, "configuration error, found } with no matching {");
2527 conftype = CONF_STR;
2530 if (tokens[1][0] == '=' && tokens[1][1] == '\0') {
2533 conftype = CONF_STR;
2536 if (tokens[2][0] == '{' && tokens[2][1] == '\0') {
2539 conftype = CONF_CBK;
2545 debugx(1, DBG_ERR, "configuration error in block %s, line starting with %s", block, tokens[0]);
2546 debugx(1, DBG_ERR, "configuration error, syntax error in line starting with %s", tokens[0]);
2550 debugx(1, DBG_ERR, "configuration error, option %s needs a non-empty value", opt);
2552 va_start(ap, block);
2553 while ((word = va_arg(ap, char *))) {
2554 type = va_arg(ap, int);
2557 str = va_arg(ap, char **);
2559 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2562 mstr = va_arg(ap, char ***);
2564 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2567 cbk = va_arg(ap, void (*)(FILE *, char *, char *, char *));
2570 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2572 if (!strcasecmp(opt, word))
2579 debugx(1, DBG_ERR, "configuration error in block %s, unknown option %s", block, opt);
2580 debugx(1, DBG_ERR, "configuration error, unknown option %s", opt);
2583 if (((type == CONF_STR || type == CONF_MSTR) && conftype != CONF_STR) ||
2584 (type == CONF_CBK && conftype != CONF_CBK)) {
2586 debugx(1, DBG_ERR, "configuration error in block %s, wrong syntax for option %s", block, opt);
2587 debugx(1, DBG_ERR, "configuration error, wrong syntax for option %s", opt);
2593 debug(DBG_DBG, "getgeneralconfig: block %s: %s = %s", block, opt, val);
2595 debug(DBG_DBG, "getgeneralconfig: %s = %s", opt, val);
2597 debugx(1, DBG_ERR, "configuration error, option %s already set to %s", opt, *str);
2598 *str = stringcopy(val, 0);
2600 debugx(1, DBG_ERR, "malloc failed");
2604 debug(DBG_DBG, "getgeneralconfig: block %s: %s = %s", block, opt, val);
2606 debug(DBG_DBG, "getgeneralconfig: %s = %s", opt, val);
2608 for (n = 0; (*mstr)[n]; n++);
2611 *mstr = realloc(*mstr, sizeof(char *) * (n + 2));
2613 debugx(1, DBG_ERR, "malloc failed");
2614 (*mstr)[n] = stringcopy(val, 0);
2615 (*mstr)[n + 1] = NULL;
2618 optval = malloc(strlen(opt) + strlen(val) + 2);
2620 debugx(1, DBG_ERR, "malloc failed");
2621 sprintf(optval, "%s %s", opt, val);
2622 cbk(f, optval, opt, val);
2626 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2631 int addmatchcertattr(struct clsrvconf *conf, char *matchcertattr) {
2634 v = matchcertattr + 20;
2635 if (strncasecmp(matchcertattr, "SubjectAltName:URI:/", 20) || !*v)
2637 /* regexp, remove optional trailing / if present */
2638 if (v[strlen(v) - 1] == '/')
2639 v[strlen(v) - 1] = '\0';
2643 conf->certuriregex = malloc(sizeof(regex_t));
2644 if (!conf->certuriregex) {
2645 debug(DBG_ERR, "malloc failed");
2648 if (regcomp(conf->certuriregex, v, REG_ICASE | REG_NOSUB)) {
2649 free(conf->certuriregex);
2650 conf->certuriregex = NULL;
2651 debug(DBG_ERR, "failed to compile regular expression %s", v);
2657 int addrewriteattr(struct clsrvconf *conf, char *rewriteattr) {
2660 v = rewriteattr + 11;
2661 if (strncasecmp(rewriteattr, "User-Name:/", 11) || !*v)
2663 /* regexp, remove optional trailing / if present */
2664 if (v[strlen(v) - 1] == '/')
2665 v[strlen(v) - 1] = '\0';
2673 conf->rewriteattrregex = malloc(sizeof(regex_t));
2674 if (!conf->rewriteattrregex) {
2675 debug(DBG_ERR, "malloc failed");
2679 conf->rewriteattrreplacement = stringcopy(w, 0);
2680 if (!conf->rewriteattrreplacement) {
2681 free(conf->rewriteattrregex);
2682 conf->rewriteattrregex = NULL;
2686 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
2687 free(conf->rewriteattrregex);
2688 conf->rewriteattrregex = NULL;
2689 free(conf->rewriteattrreplacement);
2690 conf->rewriteattrreplacement = NULL;
2691 debug(DBG_ERR, "failed to compile regular expression %s", v);
2698 void confclient_cb(FILE *f, char *block, char *opt, char *val) {
2699 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *rewriteattr = NULL;
2700 struct clsrvconf *conf;
2702 debug(DBG_DBG, "confclient_cb called for %s", block);
2704 conf = malloc(sizeof(struct clsrvconf));
2705 if (!conf || !list_push(clconfs, conf))
2706 debugx(1, DBG_ERR, "malloc failed");
2707 memset(conf, 0, sizeof(struct clsrvconf));
2709 getgeneralconfig(f, block,
2710 "type", CONF_STR, &type,
2711 "host", CONF_STR, &conf->host,
2712 "secret", CONF_STR, &conf->secret,
2713 "tls", CONF_STR, &tls,
2714 "matchcertificateattribute", CONF_STR, &matchcertattr,
2715 "rewriteattribute", CONF_STR, &rewriteattr,
2719 /* leave conf->name to be NULL for clients */
2721 conf->host = stringcopy(val, 0);
2723 if (type && !strcasecmp(type, "udp")) {
2726 } else if (type && !strcasecmp(type, "tls")) {
2727 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultclient", "default");
2729 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2730 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2731 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2735 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2740 free(matchcertattr);
2743 if (!addrewriteattr(conf, rewriteattr))
2744 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2748 if (!resolvepeer(conf, 0))
2749 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2751 if (!conf->secret) {
2752 if (conf->type == 'U')
2753 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2754 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2758 void confserver_cb(FILE *f, char *block, char *opt, char *val) {
2759 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *statusserver = NULL;
2760 struct clsrvconf *conf;
2762 debug(DBG_DBG, "confserver_cb called for %s", block);
2764 conf = malloc(sizeof(struct clsrvconf));
2765 if (!conf || !list_push(srvconfs, conf))
2766 debugx(1, DBG_ERR, "malloc failed");
2767 memset(conf, 0, sizeof(struct clsrvconf));
2769 getgeneralconfig(f, block,
2770 "type", CONF_STR, &type,
2771 "host", CONF_STR, &conf->host,
2772 "port", CONF_STR, &conf->port,
2773 "secret", CONF_STR, &conf->secret,
2774 "tls", CONF_STR, &tls,
2775 "matchcertificateattribute", CONF_STR, &matchcertattr,
2776 "StatusServer", CONF_STR, &statusserver,
2780 conf->name = stringcopy(val, 0);
2782 conf->host = stringcopy(val, 0);
2784 if (type && !strcasecmp(type, "udp")) {
2788 conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
2789 } else if (type && !strcasecmp(type, "tls")) {
2790 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultserver", "default");
2792 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2793 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2794 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2796 conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
2800 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2805 free(matchcertattr);
2807 if (!resolvepeer(conf, 0))
2808 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2810 if (!conf->secret) {
2811 if (conf->type == 'U')
2812 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2813 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2817 if (!strcasecmp(statusserver, "on"))
2818 conf->statusserver = 1;
2819 else if (strcasecmp(statusserver, "off"))
2820 debugx(1, DBG_ERR, "error in block %s, StatusServer is %s, must be on or off", block, statusserver);
2825 void confrealm_cb(FILE *f, char *block, char *opt, char *val) {
2826 char **servers = NULL, *msg = NULL;
2828 debug(DBG_DBG, "confrealm_cb called for %s", block);
2830 getgeneralconfig(f, block,
2831 "server", CONF_MSTR, &servers,
2832 "ReplyMessage", CONF_STR, &msg,
2836 addrealm(val, servers, msg);
2840 void conftls_cb(FILE *f, char *block, char *opt, char *val) {
2841 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
2843 debug(DBG_DBG, "conftls_cb called for %s", block);
2845 getgeneralconfig(f, block,
2846 "CACertificateFile", CONF_STR, &cacertfile,
2847 "CACertificatePath", CONF_STR, &cacertpath,
2848 "CertificateFile", CONF_STR, &certfile,
2849 "CertificateKeyFile", CONF_STR, &certkeyfile,
2850 "CertificateKeyPassword", CONF_STR, &certkeypwd,
2854 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
2862 void getmainconfig(const char *configfile) {
2864 char *loglevel = NULL;
2866 f = openconfigfile(configfile);
2867 memset(&options, 0, sizeof(options));
2869 clconfs = list_create();
2871 debugx(1, DBG_ERR, "malloc failed");
2873 srvconfs = list_create();
2875 debugx(1, DBG_ERR, "malloc failed");
2877 realms = list_create();
2879 debugx(1, DBG_ERR, "malloc failed");
2881 tlsconfs = list_create();
2883 debugx(1, DBG_ERR, "malloc failed");
2885 getgeneralconfig(f, NULL,
2886 "ListenUDP", CONF_STR, &options.listenudp,
2887 "ListenTCP", CONF_STR, &options.listentcp,
2888 "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
2889 "SourceUDP", CONF_STR, &options.sourceudp,
2890 "SourceTCP", CONF_STR, &options.sourcetcp,
2891 "LogLevel", CONF_STR, &loglevel,
2892 "LogDestination", CONF_STR, &options.logdestination,
2893 "Client", CONF_CBK, confclient_cb,
2894 "Server", CONF_CBK, confserver_cb,
2895 "Realm", CONF_CBK, confrealm_cb,
2896 "TLS", CONF_CBK, conftls_cb,
2903 if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
2904 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
2905 options.loglevel = *loglevel - '0';
2910 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
2913 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
2916 *configfile = optarg;
2919 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
2920 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
2921 *loglevel = *optarg - '0';
2930 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
2935 if (!(argc - optind))
2939 debug(DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
2943 int main(int argc, char **argv) {
2944 pthread_t udpserverth, udpaccserverth, udpclient4rdth, udpclient6rdth;
2945 struct list_node *entry;
2946 uint8_t foreground = 0, pretend = 0, loglevel = 0;
2947 char *configfile = NULL;
2949 debug_init("radsecproxy");
2950 debug_set_level(DEBUG_LEVEL);
2951 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
2953 debug_set_level(loglevel);
2954 getmainconfig(configfile ? configfile : CONFIG_MAIN);
2956 options.loglevel = loglevel;
2957 else if (options.loglevel)
2958 debug_set_level(options.loglevel);
2960 options.logdestination = NULL;
2962 if (!options.logdestination)
2963 options.logdestination = "x-syslog:///";
2964 debug_set_destination(options.logdestination);
2968 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
2970 if (!list_first(clconfs))
2971 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
2972 if (!list_first(srvconfs))
2973 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
2974 if (!list_first(realms))
2975 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
2977 if (!foreground && (daemon(0, 0) < 0))
2978 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
2980 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
2982 if (client_udp_count) {
2983 udp_server_replyq = newreplyq();
2984 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
2985 debugx(1, DBG_ERR, "pthread_create failed");
2986 if (options.listenaccudp)
2987 if (pthread_create(&udpaccserverth, NULL, udpaccserverrd, NULL))
2988 debugx(1, DBG_ERR, "pthread_create failed");
2991 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2992 addserver((struct clsrvconf *)entry->data);
2993 if (pthread_create(&((struct clsrvconf *)entry->data)->servers->clientth, NULL, clientwr,
2994 (void *)((struct clsrvconf *)entry->data)->servers))
2995 debugx(1, DBG_ERR, "pthread_create failed");
2997 /* srcudpres no longer needed, while srctcpres is needed later */
3002 if (udp_client4_sock >= 0)
3003 if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
3004 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
3005 if (udp_client6_sock >= 0)
3006 if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
3007 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
3009 if (client_tls_count)
3010 return tlslistener();
3012 /* just hang around doing nothing, anything to do here? */