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>
41 #include <sys/types.h>
42 #include <arpa/inet.h>
46 #include <openssl/ssl.h>
47 #include <openssl/rand.h>
48 #include <openssl/err.h>
49 #include <openssl/md5.h>
50 #include <openssl/hmac.h>
51 #include <openssl/x509v3.h>
56 #include "radsecproxy.h"
58 static struct options options;
59 struct list *clconfs, *srvconfs, *realms, *tlsconfs;
61 static int client_udp_count = 0;
62 static int client_tls_count = 0;
63 static int server_udp_count = 0;
64 static int server_tls_count = 0;
66 static struct clsrvconf *srcudpres = NULL;
67 static struct clsrvconf *srctcpres = NULL;
69 static struct replyq *udp_server_replyq = NULL;
70 static int udp_server_sock = -1;
71 static int udp_accserver_sock = -1;
72 static int udp_client4_sock = -1;
73 static int udp_client6_sock = -1;
74 static pthread_mutex_t *ssl_locks;
75 static long *ssl_lock_count;
79 /* callbacks for making OpenSSL thread safe */
80 unsigned long ssl_thread_id() {
81 return (unsigned long)pthread_self();
84 void ssl_locking_callback(int mode, int type, const char *file, int line) {
85 if (mode & CRYPTO_LOCK) {
86 pthread_mutex_lock(&ssl_locks[type]);
87 ssl_lock_count[type]++;
89 pthread_mutex_unlock(&ssl_locks[type]);
92 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
93 int pwdlen = strlen(userdata);
94 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
96 memcpy(buf, userdata, pwdlen);
100 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
105 err_cert = X509_STORE_CTX_get_current_cert(ctx);
106 err = X509_STORE_CTX_get_error(ctx);
107 depth = X509_STORE_CTX_get_error_depth(ctx);
109 if (depth > MAX_CERT_DEPTH) {
111 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
112 X509_STORE_CTX_set_error(ctx, err);
116 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
117 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
120 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
121 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
122 debug(DBG_WARN, "\tIssuer=%s", buf);
124 case X509_V_ERR_CERT_NOT_YET_VALID:
125 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
126 debug(DBG_WARN, "\tCertificate not yet valid");
128 case X509_V_ERR_CERT_HAS_EXPIRED:
129 debug(DBG_WARN, "Certificate has expired");
131 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
132 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
137 printf("certificate verify returns %d\n", ok);
142 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
143 struct addrinfo hints, *addrinfo, *res;
147 slash = conf->host ? strchr(conf->host, '/') : NULL;
151 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
155 if (*s < '0' || *s > '9') {
156 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
159 plen = atoi(slash + 1);
160 if (plen < 0 || plen > 128) {
161 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
166 memset(&hints, 0, sizeof(hints));
167 hints.ai_socktype = (conf->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
168 hints.ai_family = AF_UNSPEC;
169 hints.ai_flags = ai_flags;
170 if (!conf->host && !conf->port) {
171 /* getaddrinfo() doesn't like host and port to be NULL */
172 if (getaddrinfo(conf->host, DEFAULT_UDP_PORT, &hints, &addrinfo)) {
173 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
176 for (res = addrinfo; res; res = res->ai_next) {
177 switch (res->ai_family) {
179 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
182 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
188 hints.ai_flags |= AI_NUMERICHOST;
189 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
190 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host, conf->port);
195 switch (addrinfo->ai_family) {
198 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
199 freeaddrinfo(addrinfo);
206 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
207 freeaddrinfo(addrinfo);
210 conf->prefixlen = plen;
212 conf->prefixlen = 255;
215 freeaddrinfo(conf->addrinfo);
216 conf->addrinfo = addrinfo;
220 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
222 struct addrinfo *res;
224 for (res = addrinfo; res; res = res->ai_next) {
225 if (family != AF_UNSPEC && family != res->ai_family)
227 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
229 debug(DBG_WARN, "bindtoaddr: socket failed");
233 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
236 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
239 if (!bind(s, res->ai_addr, res->ai_addrlen))
241 debug(DBG_WARN, "bindtoaddr: bind failed");
247 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
252 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
256 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
258 debugx(1, DBG_ERR, "no ] matching initial [");
262 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
265 debugx(1, DBG_ERR, "missing host/address");
267 conf->host = stringcopy(field, p - field);
270 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
271 debugx(1, DBG_ERR, "unexpected character after ]");
274 /* port number or service name is specified */;
276 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
278 debugx(1, DBG_ERR, "syntax error, : but no following port");
279 conf->port = stringcopy(field, p - field);
281 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
285 struct clsrvconf *resolve_hostport(char type, char *lconf, char *default_port) {
286 struct clsrvconf *conf;
288 conf = malloc(sizeof(struct clsrvconf));
290 debugx(1, DBG_ERR, "malloc failed");
291 memset(conf, 0, sizeof(struct clsrvconf));
294 parsehostport(lconf, conf, default_port);
295 if (!strcmp(conf->host, "*")) {
300 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
301 if (!resolvepeer(conf, AI_PASSIVE))
302 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
306 int connecttcp(struct addrinfo *addrinfo) {
308 struct addrinfo *res;
311 for (res = addrinfo; res; res = res->ai_next) {
312 s = bindtoaddr(srctcpres->addrinfo, res->ai_family, 1, 1);
314 debug(DBG_WARN, "connecttoserver: socket failed");
317 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
319 debug(DBG_WARN, "connecttoserver: connect failed");
326 /* returns 1 if the len first bits are equal, else 0 */
327 int prefixmatch(void *a1, void *a2, uint8_t len) {
328 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
330 if (l && memcmp(a1, a2, l))
335 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
338 /* returns the config with matching address, or NULL */
339 /* if conf argument is not NULL, we only check that one */
340 struct clsrvconf *find_conf(char type, struct sockaddr *addr, struct list *confs, struct clsrvconf *conf) {
341 struct sockaddr_in6 *sa6 = NULL;
342 struct in_addr *a4 = NULL;
343 struct addrinfo *res;
344 struct list_node *entry;
346 if (addr->sa_family == AF_INET6) {
347 sa6 = (struct sockaddr_in6 *)addr;
348 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
349 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
353 a4 = &((struct sockaddr_in *)addr)->sin_addr;
356 if (conf->type == type) {
357 if (conf->prefixlen == 255) {
358 for (res = conf->addrinfo; res; res = res->ai_next)
359 if ((a4 && res->ai_family == AF_INET &&
360 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
361 (sa6 && res->ai_family == AF_INET6 &&
362 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
365 res = conf->addrinfo;
367 ((a4 && res->ai_family == AF_INET &&
368 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
369 (sa6 && res->ai_family == AF_INET6 &&
370 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
377 for (entry = list_first(confs); entry; entry = list_next(entry)) {
378 conf = (struct clsrvconf *)entry->data;
379 if (conf->type == type) {
380 if (conf->prefixlen == 255) {
381 for (res = conf->addrinfo; res; res = res->ai_next)
382 if ((a4 && res->ai_family == AF_INET &&
383 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
384 (sa6 && res->ai_family == AF_INET6 &&
385 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
388 res = conf->addrinfo;
390 ((a4 && res->ai_family == AF_INET &&
391 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
392 (sa6 && res->ai_family == AF_INET6 &&
393 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
401 struct replyq *newreplyq() {
402 struct replyq *replyq;
404 replyq = malloc(sizeof(struct replyq));
406 debugx(1, DBG_ERR, "malloc failed");
407 replyq->replies = list_create();
408 if (!replyq->replies)
409 debugx(1, DBG_ERR, "malloc failed");
410 pthread_mutex_init(&replyq->mutex, NULL);
411 pthread_cond_init(&replyq->cond, NULL);
415 struct client *addclient(struct clsrvconf *conf) {
416 struct client *new = malloc(sizeof(struct client));
419 debug(DBG_ERR, "malloc failed");
422 if (!conf->clients) {
423 conf->clients = list_create();
424 if (!conf->clients) {
425 debug(DBG_ERR, "malloc failed");
430 memset(new, 0, sizeof(struct client));
432 new->replyq = conf->type == 'T' ? newreplyq() : udp_server_replyq;
434 list_push(conf->clients, new);
438 void removeclient(struct client *client) {
439 if (!client || !client->conf->clients)
442 list_removedata(client->conf->clients, client);
446 void addserver(struct clsrvconf *conf) {
448 debugx(1, DBG_ERR, "addserver: currently works with just one server per conf");
450 conf->servers = malloc(sizeof(struct server));
452 debugx(1, DBG_ERR, "malloc failed");
453 memset(conf->servers, 0, sizeof(struct server));
454 conf->servers->conf = conf;
456 if (conf->type == 'U') {
458 srcudpres = resolve_hostport('U', options.sourceudp, NULL);
459 switch (conf->addrinfo->ai_family) {
461 if (udp_client4_sock < 0) {
462 udp_client4_sock = bindtoaddr(srcudpres->addrinfo, AF_INET, 0, 1);
463 if (udp_client4_sock < 0)
464 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
466 conf->servers->sock = udp_client4_sock;
469 if (udp_client6_sock < 0) {
470 udp_client6_sock = bindtoaddr(srcudpres->addrinfo, AF_INET6, 0, 1);
471 if (udp_client6_sock < 0)
472 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
474 conf->servers->sock = udp_client6_sock;
477 debugx(1, DBG_ERR, "addserver: unsupported address family");
482 srctcpres = resolve_hostport('T', options.sourcetcp, NULL);
483 conf->servers->sock = -1;
486 pthread_mutex_init(&conf->servers->lock, NULL);
487 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
488 if (!conf->servers->requests)
489 debugx(1, DBG_ERR, "malloc failed");
490 conf->servers->newrq = 0;
491 pthread_mutex_init(&conf->servers->newrq_mutex, NULL);
492 pthread_cond_init(&conf->servers->newrq_cond, NULL);
495 /* exactly one of client and server must be non-NULL */
496 /* should probably take peer list (client(s) or server(s)) as argument instead */
497 /* if *peer == NULL we return who we received from, else require it to be from peer */
498 /* return from in sa if not NULL */
499 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
501 unsigned char buf[65536], *rad;
502 struct sockaddr_storage from;
503 socklen_t fromlen = sizeof(from);
505 struct list_node *node;
508 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
510 debug(DBG_WARN, "radudpget: recv failed");
513 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
516 debug(DBG_WARN, "radudpget: packet too small");
522 debug(DBG_WARN, "radudpget: length too small");
527 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
531 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
535 p = find_conf('U', (struct sockaddr *)&from, NULL, (*client)->conf);
537 p = find_conf('U', (struct sockaddr *)&from, clconfs, NULL);
540 p = find_conf('U', (struct sockaddr *)&from, NULL, (*server)->conf);
542 p = find_conf('U', (struct sockaddr *)&from, srvconfs, NULL);
545 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer, ignoring");
551 debug(DBG_ERR, "radudpget: malloc failed");
555 if (client && !*client) {
556 node = list_first(p->clients);
557 *client = node ? (struct client *)node->data : addclient(p);
562 } else if (server && !*server)
563 *server = p->servers;
567 memcpy(rad, buf, len);
573 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
574 int loc, i, l, n, r = 0;
577 STACK_OF(GENERAL_NAME) *alt;
580 debug(DBG_DBG, "subjectaltnameaddr");
582 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
586 ex = X509_get_ext(cert, loc);
587 alt = X509V3_EXT_d2i(ex);
591 n = sk_GENERAL_NAME_num(alt);
592 for (i = 0; i < n; i++) {
593 gn = sk_GENERAL_NAME_value(alt, i);
594 if (gn->type != GEN_IPADD)
597 v = (char *)ASN1_STRING_data(gn->d.ia5);
598 l = ASN1_STRING_length(gn->d.ia5);
599 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
600 && !memcmp(v, &addr, l)) {
605 GENERAL_NAMES_free(alt);
609 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
610 int loc, i, l, n, r = 0;
613 STACK_OF(GENERAL_NAME) *alt;
616 debug(DBG_DBG, "subjectaltnameregexp");
618 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
622 ex = X509_get_ext(cert, loc);
623 alt = X509V3_EXT_d2i(ex);
627 n = sk_GENERAL_NAME_num(alt);
628 for (i = 0; i < n; i++) {
629 gn = sk_GENERAL_NAME_value(alt, i);
630 if (gn->type != type)
633 v = (char *)ASN1_STRING_data(gn->d.ia5);
634 l = ASN1_STRING_length(gn->d.ia5);
638 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
641 if (memcmp(v, exact, l))
644 s = stringcopy((char *)v, l);
646 debug(DBG_ERR, "malloc failed");
649 if (regexec(regex, s, 0, NULL, 0)) {
658 GENERAL_NAMES_free(alt);
662 int tlsverifycert(SSL *ssl, struct clsrvconf *conf) {
669 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
671 struct in6_addr addr;
673 if (SSL_get_verify_result(ssl) != X509_V_OK) {
674 debug(DBG_ERR, "tlsverifycert: basic validation failed");
675 while ((error = ERR_get_error()))
676 debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
680 cert = SSL_get_peer_certificate(ssl);
682 debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
686 if (conf->prefixlen == 255) {
687 if (inet_pton(AF_INET, conf->host, &addr))
689 else if (inet_pton(AF_INET6, conf->host, &addr))
692 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
696 debug(DBG_DBG, "tlsverifycert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
699 debug(DBG_DBG, "tlsverifycert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
701 nm = X509_get_subject_name(cert);
704 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
707 e = X509_NAME_get_entry(nm, loc);
708 s = X509_NAME_ENTRY_get_data(e);
709 v = (char *) ASN1_STRING_data(s);
710 l = ASN1_STRING_length(s);
714 printfchars(NULL, "cn", NULL, v, l);
716 if (l == strlen(conf->host) && !strncasecmp(conf->host, v, l)) {
718 debug(DBG_DBG, "tlsverifycert: Found cn matching host %s", conf->host);
724 debug(DBG_ERR, "tlsverifycert: cn not matching host %s", conf->host);
729 if (conf->certuriregex) {
730 r = subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex);
732 debug(DBG_DBG, "tlsverifycert: subjectaltname URI not matching regex");
736 debug(DBG_DBG, "tlsverifycert: subjectaltname URI matching regex");
742 void tlsconnect(struct server *server, struct timeval *when, char *text) {
746 debug(DBG_DBG, "tlsconnect called from %s", text);
747 pthread_mutex_lock(&server->lock);
748 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
749 /* already reconnected, nothing to do */
750 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
751 pthread_mutex_unlock(&server->lock);
755 debug(DBG_DBG, "tlsconnect %s", text);
758 gettimeofday(&now, NULL);
759 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
760 if (server->connectionok) {
761 server->connectionok = 0;
763 } else if (elapsed < 5)
765 else if (elapsed < 300) {
766 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
768 } else if (elapsed < 100000) {
769 debug(DBG_INFO, "tlsconnect: sleeping %ds", 600);
772 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
773 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
774 if (server->sock >= 0)
776 if ((server->sock = connecttcp(server->conf->addrinfo)) < 0) {
777 debug(DBG_ERR, "tlsconnect: connecttcp failed");
781 SSL_free(server->ssl);
782 server->ssl = SSL_new(server->conf->ssl_ctx);
783 SSL_set_fd(server->ssl, server->sock);
784 if (SSL_connect(server->ssl) > 0 && tlsverifycert(server->ssl, server->conf))
787 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
788 gettimeofday(&server->lastconnecttry, NULL);
789 pthread_mutex_unlock(&server->lock);
792 unsigned char *radtlsget(SSL *ssl) {
794 unsigned char buf[4], *rad;
797 for (total = 0; total < 4; total += cnt) {
798 cnt = SSL_read(ssl, buf + total, 4 - total);
800 debug(DBG_ERR, "radtlsget: connection lost");
801 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
802 /* remote end sent close_notify, send one back */
812 debug(DBG_ERR, "radtlsget: malloc failed");
817 for (; total < len; total += cnt) {
818 cnt = SSL_read(ssl, rad + total, len - total);
820 debug(DBG_ERR, "radtlsget: connection lost");
821 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
822 /* remote end sent close_notify, send one back */
834 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
837 debug(DBG_DBG, "radtlsget: got %d bytes", total);
841 int clientradput(struct server *server, unsigned char *rad) {
845 struct timeval lastconnecttry;
846 struct clsrvconf *conf = server->conf;
849 if (conf->type == 'U') {
850 if (sendto(server->sock, rad, len, 0, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen) >= 0) {
851 debug(DBG_DBG, "clienradput: sent UDP of length %d to %s port %s", len, conf->host, conf->port);
854 debug(DBG_WARN, "clientradput: send failed");
858 lastconnecttry = server->lastconnecttry;
859 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
860 while ((error = ERR_get_error()))
861 debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
862 tlsconnect(server, &lastconnecttry, "clientradput");
863 lastconnecttry = server->lastconnecttry;
866 server->connectionok = 1;
867 debug(DBG_DBG, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
871 int radsign(unsigned char *rad, unsigned char *sec) {
872 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
873 static unsigned char first = 1;
874 static EVP_MD_CTX mdctx;
878 pthread_mutex_lock(&lock);
880 EVP_MD_CTX_init(&mdctx);
884 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
885 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
886 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
887 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
889 pthread_mutex_unlock(&lock);
893 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
894 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
895 static unsigned char first = 1;
896 static EVP_MD_CTX mdctx;
897 unsigned char hash[EVP_MAX_MD_SIZE];
901 pthread_mutex_lock(&lock);
903 EVP_MD_CTX_init(&mdctx);
909 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
910 EVP_DigestUpdate(&mdctx, rad, 4) &&
911 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
912 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
913 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
914 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
916 !memcmp(hash, rad + 4, 16));
917 pthread_mutex_unlock(&lock);
921 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
922 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
923 static unsigned char first = 1;
924 static HMAC_CTX hmacctx;
926 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
928 pthread_mutex_lock(&lock);
930 HMAC_CTX_init(&hmacctx);
934 memcpy(auth, authattr, 16);
935 memset(authattr, 0, 16);
937 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
938 HMAC_Update(&hmacctx, rad, RADLEN(rad));
939 HMAC_Final(&hmacctx, hash, &md_len);
940 memcpy(authattr, auth, 16);
942 debug(DBG_WARN, "message auth computation failed");
943 pthread_mutex_unlock(&lock);
947 if (memcmp(auth, hash, 16)) {
948 debug(DBG_WARN, "message authenticator, wrong value");
949 pthread_mutex_unlock(&lock);
953 pthread_mutex_unlock(&lock);
957 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
958 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
959 static unsigned char first = 1;
960 static HMAC_CTX hmacctx;
966 pthread_mutex_lock(&lock);
968 HMAC_CTX_init(&hmacctx);
972 memset(authattrval, 0, 16);
974 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
975 HMAC_Update(&hmacctx, rad, RADLEN(rad));
976 HMAC_Final(&hmacctx, authattrval, &md_len);
978 debug(DBG_WARN, "message auth computation failed");
979 pthread_mutex_unlock(&lock);
983 pthread_mutex_unlock(&lock);
987 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
989 if (ATTRTYPE(attrs) == type)
991 length -= ATTRLEN(attrs);
992 attrs += ATTRLEN(attrs);
997 void freerqdata(struct request *rq) {
998 if (rq->origusername)
999 free(rq->origusername);
1004 void sendrq(struct server *to, struct request *rq) {
1008 pthread_mutex_lock(&to->newrq_mutex);
1009 /* might simplify if only try nextid, might be ok */
1010 for (i = to->nextid; i < MAX_REQUESTS; i++)
1011 if (!to->requests[i].buf)
1013 if (i == MAX_REQUESTS) {
1014 for (i = 0; i < to->nextid; i++)
1015 if (!to->requests[i].buf)
1017 if (i == to->nextid) {
1018 debug(DBG_WARN, "No room in queue, dropping request");
1020 pthread_mutex_unlock(&to->newrq_mutex);
1025 rq->buf[1] = (char)i;
1027 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1028 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1030 pthread_mutex_unlock(&to->newrq_mutex);
1034 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1035 to->requests[i] = *rq;
1040 debug(DBG_DBG, "signalling client writer");
1041 pthread_cond_signal(&to->newrq_cond);
1043 pthread_mutex_unlock(&to->newrq_mutex);
1046 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
1047 struct reply *reply;
1050 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1052 debug(DBG_WARN, "sendreply: failed to sign message");
1056 reply = malloc(sizeof(struct reply));
1059 debug(DBG_ERR, "sendreply: malloc failed");
1062 memset(reply, 0, sizeof(struct reply));
1065 reply->tosa = *tosa;
1067 pthread_mutex_lock(&to->replyq->mutex);
1069 first = list_first(to->replyq->replies) == NULL;
1071 if (!list_push(to->replyq->replies, reply)) {
1072 pthread_mutex_unlock(&to->replyq->mutex);
1075 debug(DBG_ERR, "sendreply: malloc failed");
1080 debug(DBG_DBG, "signalling server writer");
1081 pthread_cond_signal(&to->replyq->cond);
1083 pthread_mutex_unlock(&to->replyq->mutex);
1086 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1087 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1088 static unsigned char first = 1;
1089 static EVP_MD_CTX mdctx;
1090 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1091 unsigned int md_len;
1092 uint8_t i, offset = 0, out[128];
1094 pthread_mutex_lock(&lock);
1096 EVP_MD_CTX_init(&mdctx);
1102 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1103 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1104 !EVP_DigestUpdate(&mdctx, input, 16) ||
1105 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1107 pthread_mutex_unlock(&lock);
1110 for (i = 0; i < 16; i++)
1111 out[offset + i] = hash[i] ^ in[offset + i];
1112 input = out + offset - 16;
1117 memcpy(in, out, len);
1118 pthread_mutex_unlock(&lock);
1122 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1123 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1124 static unsigned char first = 1;
1125 static EVP_MD_CTX mdctx;
1126 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1127 unsigned int md_len;
1128 uint8_t i, offset = 0, out[128];
1130 pthread_mutex_lock(&lock);
1132 EVP_MD_CTX_init(&mdctx);
1138 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1139 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1140 !EVP_DigestUpdate(&mdctx, input, 16) ||
1141 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1143 pthread_mutex_unlock(&lock);
1146 for (i = 0; i < 16; i++)
1147 out[offset + i] = hash[i] ^ in[offset + i];
1148 input = in + offset;
1153 memcpy(in, out, len);
1154 pthread_mutex_unlock(&lock);
1158 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1159 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1160 static unsigned char first = 1;
1161 static EVP_MD_CTX mdctx;
1162 unsigned char hash[EVP_MAX_MD_SIZE];
1163 unsigned int md_len;
1166 pthread_mutex_lock(&lock);
1168 EVP_MD_CTX_init(&mdctx);
1173 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1174 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1175 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1178 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1179 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1180 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1181 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1182 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1183 pthread_mutex_unlock(&lock);
1188 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1191 for (i = 0; i < 16; i++)
1194 for (offset = 16; offset < len; offset += 16) {
1196 printf("text + offset - 16 c(%d): ", offset / 16);
1197 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1199 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1200 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1201 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1202 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1204 pthread_mutex_unlock(&lock);
1208 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1211 for (i = 0; i < 16; i++)
1212 text[offset + i] ^= hash[i];
1216 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1219 pthread_mutex_unlock(&lock);
1223 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1224 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1225 static unsigned char first = 1;
1226 static EVP_MD_CTX mdctx;
1227 unsigned char hash[EVP_MAX_MD_SIZE];
1228 unsigned int md_len;
1232 pthread_mutex_lock(&lock);
1234 EVP_MD_CTX_init(&mdctx);
1239 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1240 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1241 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1244 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1245 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1246 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1247 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1248 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1249 pthread_mutex_unlock(&lock);
1254 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1257 for (i = 0; i < 16; i++)
1258 plain[i] = text[i] ^ hash[i];
1260 for (offset = 16; offset < len; offset += 16) {
1262 printf("text + offset - 16 c(%d): ", offset / 16);
1263 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1265 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1266 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1267 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1268 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1270 pthread_mutex_unlock(&lock);
1274 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1277 for (i = 0; i < 16; i++)
1278 plain[offset + i] = text[offset + i] ^ hash[i];
1281 memcpy(text, plain, len);
1283 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1286 pthread_mutex_unlock(&lock);
1290 struct realm *id2realm(char *id, uint8_t len) {
1291 struct list_node *entry;
1292 struct realm *realm;
1294 for (entry = list_first(realms); entry; entry = list_next(entry)) {
1295 realm = (struct realm *)entry->data;
1296 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1297 debug(DBG_DBG, "found matching realm: %s", realm->name);
1304 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
1307 pthread_mutex_lock(&to->newrq_mutex);
1308 for (i = 0; i < MAX_REQUESTS; i++)
1309 if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
1311 pthread_mutex_unlock(&to->newrq_mutex);
1313 return i < MAX_REQUESTS;
1316 int attrvalidate(unsigned char *attrs, int length) {
1317 while (length > 1) {
1318 if (ATTRLEN(attrs) < 2) {
1319 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1322 length -= ATTRLEN(attrs);
1324 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1327 attrs += ATTRLEN(attrs);
1330 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1334 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1335 if (len < 16 || len > 128 || len % 16) {
1336 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1340 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1341 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1345 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1347 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1348 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1354 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1357 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1358 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1361 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1362 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1368 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1369 char *oldsecret, char *newsecret) {
1370 unsigned char *attr;
1372 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1373 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1374 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1380 /* returns a pointer to the resized attribute value */
1381 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1382 uint8_t *attrs, *attr, vallen;
1386 len = RADLEN(*buf) - 20;
1389 attr = attrget(attrs, len, type);
1393 vallen = ATTRVALLEN(attr);
1394 if (vallen == newvallen)
1397 len += newvallen - vallen;
1398 if (newvallen > vallen) {
1399 new = realloc(*buf, len);
1401 debug(DBG_ERR, "resizeattr: malloc failed");
1410 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1411 attr[1] = newvallen + 2;
1412 ((uint16_t *)*buf)[1] = htons(len + 20);
1416 int rewriteusername(struct request *rq, char *in) {
1417 size_t nmatch = 10, reslen = 0, start = 0;
1418 regmatch_t pmatch[10], *pfield;
1420 unsigned char *result;
1421 char *out = rq->from->conf->rewriteattrreplacement;
1423 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1424 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1428 rq->origusername = stringcopy(in, 0);
1429 if (!rq->origusername)
1432 for (i = start; out[i]; i++) {
1433 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1434 pfield = &pmatch[out[i + 1] - '0'];
1435 if (pfield->rm_so >= 0) {
1436 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1442 reslen += i - start;
1444 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1450 for (i = start; out[i]; i++) {
1451 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1452 pfield = &pmatch[out[i + 1] - '0'];
1453 if (pfield->rm_so >= 0) {
1454 memcpy(result + reslen, out + start, i - start);
1455 reslen += i - start;
1456 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1457 reslen += pfield->rm_eo - pfield->rm_so;
1464 memcpy(result + reslen, out + start, i - start);
1465 reslen += i - start;
1466 memcpy(in, result, reslen);
1471 void acclog(unsigned char *attrs, int length, char *host) {
1472 unsigned char *attr;
1475 attr = attrget(attrs, length, RAD_Attr_User_Name);
1477 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1480 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1481 username[ATTRVALLEN(attr)] = '\0';
1482 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1485 void respondaccounting(struct request *rq) {
1486 unsigned char *resp;
1490 debug(DBG_ERR, "respondstatusserver: malloc failed");
1493 memcpy(resp, rq->buf, 20);
1494 resp[0] = RAD_Accounting_Response;
1497 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1498 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1501 void respondstatusserver(struct request *rq) {
1502 unsigned char *resp;
1506 debug(DBG_ERR, "respondstatusserver: malloc failed");
1509 memcpy(resp, rq->buf, 20);
1510 resp[0] = RAD_Access_Accept;
1513 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1514 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1517 void respondreject(struct request *rq, char *message) {
1518 unsigned char *resp;
1521 if (message && *message)
1522 len += 2 + strlen(message);
1526 debug(DBG_ERR, "respondreject: malloc failed");
1529 memcpy(resp, rq->buf, 20);
1530 resp[0] = RAD_Access_Reject;
1531 *(uint16_t *)(resp + 2) = htons(len);
1532 if (message && *message) {
1533 resp[20] = RAD_Attr_Reply_Message;
1534 resp[21] = len - 20;
1535 memcpy(resp + 22, message, len - 22);
1537 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1540 struct server *realm2server(struct realm *realm) {
1541 struct list_node *entry;
1542 struct server *server, *best = NULL;
1544 for (entry = list_first(realm->srvconfs); entry; entry = list_next(entry)) {
1545 server = ((struct clsrvconf *)entry->data)->servers;
1546 if (!server->connectionok)
1548 if (!server->loststatsrv)
1554 if (server->loststatsrv < best->loststatsrv)
1560 void radsrv(struct request *rq) {
1561 uint8_t code, id, *auth, *attrs, *attr;
1563 struct server *to = NULL;
1565 unsigned char newauth[16];
1566 struct realm *realm = NULL;
1568 code = *(uint8_t *)rq->buf;
1569 id = *(uint8_t *)(rq->buf + 1);
1570 len = RADLEN(rq->buf);
1571 auth = (uint8_t *)(rq->buf + 4);
1573 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1575 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1576 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1582 attrs = rq->buf + 20;
1584 if (!attrvalidate(attrs, len)) {
1585 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1590 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1591 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
1592 debug(DBG_WARN, "radsrv: message authentication failed");
1597 if (code != RAD_Access_Request) {
1599 case RAD_Accounting_Request:
1600 acclog(attrs, len, rq->from->conf->host);
1601 respondaccounting(rq);
1603 case RAD_Status_Server:
1604 respondstatusserver(rq);
1611 /* code == RAD_Access_Request */
1612 attr = attrget(attrs, len, RAD_Attr_User_Name);
1614 debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1618 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1619 username[ATTRVALLEN(attr)] = '\0';
1621 if (rq->from->conf->rewriteattrregex) {
1622 if (!rewriteusername(rq, username)) {
1623 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1627 len = RADLEN(rq->buf) - 20;
1628 auth = (uint8_t *)(rq->buf + 4);
1629 attrs = rq->buf + 20;
1632 if (rq->origusername)
1633 debug(DBG_DBG, "Access Request with username: %s (originally %s)", username, rq->origusername);
1635 debug(DBG_DBG, "Access Request with username: %s", username);
1637 realm = id2realm(username, strlen(username));
1639 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1644 to = realm2server(realm);
1645 if (to && rqinqueue(to, rq->from, id)) {
1646 debug(DBG_INFO, "radsrv: already got request from host %s with id %d, ignoring", rq->from->conf->host, id);
1652 if (realm->message) {
1653 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, username);
1654 respondreject(rq, realm->message);
1660 if (!RAND_bytes(newauth, 16)) {
1661 debug(DBG_WARN, "radsrv: failed to generate random auth");
1667 printfchars(NULL, "auth", "%02x ", auth, 16);
1670 attr = attrget(attrs, len, RAD_Attr_User_Password);
1672 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1673 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1679 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1681 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1682 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1689 memcpy(rq->origauth, auth, 16);
1690 memcpy(auth, newauth, 16);
1694 int replyh(struct server *server, unsigned char *buf) {
1695 struct client *from;
1698 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
1699 struct sockaddr_storage fromsa;
1702 server->connectionok = 1;
1703 server->loststatsrv = 0;
1705 i = buf[1]; /* i is the id */
1708 case RAD_Access_Accept:
1709 debug(DBG_DBG, "got Access Accept with id %d", i);
1711 case RAD_Access_Reject:
1712 debug(DBG_DBG, "got Access Reject with id %d", i);
1714 case RAD_Access_Challenge:
1715 debug(DBG_DBG, "got Access Challenge with id %d", i);
1718 debug(DBG_INFO, "replyh: discarding, only accept access accept, access reject and access challenge messages");
1722 rq = server->requests + i;
1724 pthread_mutex_lock(&server->newrq_mutex);
1725 if (!rq->buf || !rq->tries) {
1726 pthread_mutex_unlock(&server->newrq_mutex);
1727 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
1732 pthread_mutex_unlock(&server->newrq_mutex);
1733 debug(DBG_INFO, "replyh: already received, ignoring reply");
1737 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
1738 pthread_mutex_unlock(&server->newrq_mutex);
1739 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
1744 len = RADLEN(buf) - 20;
1747 if (!attrvalidate(attrs, len)) {
1748 pthread_mutex_unlock(&server->newrq_mutex);
1749 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
1753 /* Message Authenticator */
1754 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1756 if (ATTRVALLEN(messageauth) != 16) {
1757 pthread_mutex_unlock(&server->newrq_mutex);
1758 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
1761 memcpy(tmp, buf + 4, 16);
1762 memcpy(buf + 4, rq->buf + 4, 16);
1763 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
1764 pthread_mutex_unlock(&server->newrq_mutex);
1765 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
1768 memcpy(buf + 4, tmp, 16);
1769 debug(DBG_DBG, "replyh: message auth ok");
1772 if (*rq->buf == RAD_Status_Server) {
1774 pthread_mutex_unlock(&server->newrq_mutex);
1775 debug(DBG_INFO, "replyh: got status server response from %s", server->conf->host);
1780 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1781 if (ATTRVALLEN(attr) <= 4)
1784 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
1787 sublen = ATTRVALLEN(attr) - 4;
1788 subattrs = ATTRVAL(attr) + 4;
1789 if (!attrvalidate(subattrs, sublen) ||
1790 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1791 rq, server->conf->secret, from->conf->secret) ||
1792 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1793 rq, server->conf->secret, from->conf->secret))
1797 pthread_mutex_unlock(&server->newrq_mutex);
1798 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1802 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject) {
1803 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
1804 /* we know the attribute exists */
1805 memcpy(tmp, ATTRVAL(attr), ATTRVALLEN(attr));
1806 tmp[ATTRVALLEN(attr)] = '\0';
1808 case RAD_Access_Accept:
1809 if (rq->origusername)
1810 debug(DBG_INFO, "Access Accept for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1812 debug(DBG_INFO, "Access Accept for %s from %s", tmp, server->conf->host);
1814 case RAD_Access_Reject:
1815 if (rq->origusername)
1816 debug(DBG_INFO, "Access Reject for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1818 debug(DBG_INFO, "Access Reject for %s from %s", tmp, server->conf->host);
1823 buf[1] = (char)rq->origid;
1824 memcpy(buf + 4, rq->origauth, 16);
1826 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1829 if (rq->origusername) {
1830 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
1832 pthread_mutex_unlock(&server->newrq_mutex);
1833 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1836 memcpy(username, rq->origusername, strlen(rq->origusername));
1837 len = RADLEN(buf) - 20;
1840 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1844 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
1845 pthread_mutex_unlock(&server->newrq_mutex);
1846 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
1849 debug(DBG_DBG, "replyh: computed messageauthattr");
1852 if (from->conf->type == 'U')
1853 fromsa = rq->fromsa;
1854 /* once we set received = 1, rq may be reused */
1856 pthread_mutex_unlock(&server->newrq_mutex);
1858 debug(DBG_DBG, "replyh: giving packet back to where it came from");
1859 sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
1863 void *udpclientrd(void *arg) {
1864 struct server *server;
1866 int *s = (int *)arg;
1870 buf = radudpget(*s, NULL, &server, NULL);
1871 if (!replyh(server, buf))
1876 void *tlsclientrd(void *arg) {
1877 struct server *server = (struct server *)arg;
1879 struct timeval lastconnecttry;
1882 /* yes, lastconnecttry is really necessary */
1883 lastconnecttry = server->lastconnecttry;
1884 buf = radtlsget(server->ssl);
1886 tlsconnect(server, &lastconnecttry, "clientrd");
1890 if (!replyh(server, buf))
1895 void *clientwr(void *arg) {
1896 struct server *server = (struct server *)arg;
1898 pthread_t tlsclientrdth;
1901 struct timeval now, lastsend;
1902 struct timespec timeout;
1903 struct request statsrvrq;
1904 unsigned char statsrvbuf[38];
1906 memset(&timeout, 0, sizeof(struct timespec));
1908 if (server->conf->statusserver) {
1909 memset(&statsrvrq, 0, sizeof(struct request));
1910 memset(statsrvbuf, 0, sizeof(statsrvbuf));
1911 statsrvbuf[0] = RAD_Status_Server;
1913 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
1914 statsrvbuf[21] = 18;
1915 gettimeofday(&lastsend, NULL);
1918 if (server->conf->type == 'U') {
1919 server->connectionok = 1;
1921 tlsconnect(server, NULL, "new client");
1922 server->connectionok = 1;
1923 if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server))
1924 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
1928 pthread_mutex_lock(&server->newrq_mutex);
1929 if (!server->newrq) {
1930 gettimeofday(&now, NULL);
1931 if (server->conf->statusserver) {
1932 /* random 0-7 seconds */
1933 RAND_bytes(&rnd, 1);
1935 if (!timeout.tv_sec || timeout.tv_sec - now.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
1936 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
1938 if (timeout.tv_sec) {
1939 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1940 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1943 debug(DBG_DBG, "clientwr: waiting for new request");
1944 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1947 if (server->newrq) {
1948 debug(DBG_DBG, "clientwr: got new request");
1951 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1952 pthread_mutex_unlock(&server->newrq_mutex);
1954 for (i = 0; i < MAX_REQUESTS; i++) {
1955 pthread_mutex_lock(&server->newrq_mutex);
1956 while (i < MAX_REQUESTS && !server->requests[i].buf)
1958 if (i == MAX_REQUESTS) {
1959 pthread_mutex_unlock(&server->newrq_mutex);
1962 rq = server->requests + i;
1965 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
1967 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
1969 /* setting this to NULL means that it can be reused */
1972 pthread_mutex_unlock(&server->newrq_mutex);
1976 gettimeofday(&now, NULL);
1977 if (now.tv_sec < rq->expiry.tv_sec) {
1978 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1979 timeout.tv_sec = rq->expiry.tv_sec;
1980 pthread_mutex_unlock(&server->newrq_mutex);
1984 if (rq->tries == (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
1985 ? 1 : REQUEST_RETRIES)) {
1986 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1987 if (*rq->buf == RAD_Status_Server) {
1988 debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->conf->host);
1989 if (server->loststatsrv < 255)
1990 server->loststatsrv++;
1993 /* setting this to NULL means that it can be reused */
1995 pthread_mutex_unlock(&server->newrq_mutex);
1998 pthread_mutex_unlock(&server->newrq_mutex);
2000 rq->expiry.tv_sec = now.tv_sec +
2001 (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
2002 ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
2003 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2004 timeout.tv_sec = rq->expiry.tv_sec;
2006 clientradput(server, server->requests[i].buf);
2007 gettimeofday(&lastsend, NULL);
2009 if (server->conf->statusserver) {
2010 gettimeofday(&now, NULL);
2011 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
2012 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2013 debug(DBG_WARN, "clientwr: failed to generate random auth");
2016 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2017 if (!statsrvrq.buf) {
2018 debug(DBG_ERR, "clientwr: malloc failed");
2021 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2022 debug(DBG_DBG, "clientwr: sending status server to %s", server->conf->host);
2023 lastsend.tv_sec = now.tv_sec;
2024 sendrq(server, &statsrvrq);
2030 void *udpserverwr(void *arg) {
2031 struct replyq *replyq = udp_server_replyq;
2032 struct reply *reply;
2035 pthread_mutex_lock(&replyq->mutex);
2036 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2037 debug(DBG_DBG, "udp server writer, waiting for signal");
2038 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2039 debug(DBG_DBG, "udp server writer, got signal");
2041 pthread_mutex_unlock(&replyq->mutex);
2043 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
2044 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2045 debug(DBG_WARN, "sendudp: send failed");
2051 void *udpserverrd(void *arg) {
2053 pthread_t udpserverwrth;
2054 struct clsrvconf *listenres;
2056 listenres = resolve_hostport('U', options.listenudp, DEFAULT_UDP_PORT);
2057 if ((udp_server_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2058 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2060 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
2061 listenres->host ? listenres->host : "*", listenres->port);
2064 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
2065 debugx(1, DBG_ERR, "pthread_create failed");
2068 memset(&rq, 0, sizeof(struct request));
2069 rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
2074 void *udpaccserverrd(void *arg) {
2076 struct clsrvconf *listenres;
2078 listenres = resolve_hostport('U', options.listenaccudp, DEFAULT_UDP_PORT);
2079 if ((udp_accserver_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2080 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2082 debug(DBG_WARN, "udpaccserverrd: listening for UDP on %s:%s",
2083 listenres->host ? listenres->host : "*", listenres->port);
2087 memset(&rq, 0, sizeof(struct request));
2088 rq.buf = radudpget(udp_accserver_sock, &rq.from, NULL, &rq.fromsa);
2089 if (*(uint8_t *)rq.buf == RAD_Accounting_Request) {
2093 debug(DBG_INFO, "udpaccserverrd: got something other than accounting-request, ignoring");
2098 void *tlsserverwr(void *arg) {
2100 unsigned long error;
2101 struct client *client = (struct client *)arg;
2102 struct replyq *replyq;
2103 struct reply *reply;
2105 debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
2106 replyq = client->replyq;
2108 pthread_mutex_lock(&replyq->mutex);
2109 while (!list_first(replyq->replies)) {
2111 debug(DBG_DBG, "tls server writer, waiting for signal");
2112 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2113 debug(DBG_DBG, "tls server writer, got signal");
2116 /* ssl might have changed while waiting */
2117 pthread_mutex_unlock(&replyq->mutex);
2118 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2122 reply = (struct reply *)list_shift(replyq->replies);
2123 pthread_mutex_unlock(&replyq->mutex);
2124 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2126 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
2127 cnt, RADLEN(reply->buf));
2129 while ((error = ERR_get_error()))
2130 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2136 void *tlsserverrd(void *arg) {
2138 unsigned long error;
2140 struct client *client = (struct client *)arg;
2141 pthread_t tlsserverwrth;
2144 debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2147 if (SSL_accept(ssl) <= 0) {
2148 while ((error = ERR_get_error()))
2149 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2150 debug(DBG_ERR, "SSL_accept failed");
2153 if (tlsverifycert(client->ssl, client->conf)) {
2154 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2155 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2159 memset(&rq, 0, sizeof(struct request));
2160 rq.buf = radtlsget(client->ssl);
2163 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2167 debug(DBG_ERR, "tlsserverrd: connection lost");
2168 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2170 pthread_mutex_lock(&client->replyq->mutex);
2171 pthread_cond_signal(&client->replyq->cond);
2172 pthread_mutex_unlock(&client->replyq->mutex);
2173 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2174 pthread_join(tlsserverwrth, NULL);
2178 s = SSL_get_fd(ssl);
2180 shutdown(s, SHUT_RDWR);
2182 debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->conf->host);
2183 removeclient(client);
2188 pthread_t tlsserverth;
2190 struct sockaddr_storage from;
2191 size_t fromlen = sizeof(from);
2192 struct clsrvconf *conf;
2193 struct client *client;
2194 struct clsrvconf *listenres;
2196 listenres = resolve_hostport('T', options.listentcp, DEFAULT_TLS_PORT);
2197 if ((s = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2198 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
2201 debug(DBG_WARN, "listening for incoming TCP on %s:%s", listenres->host ? listenres->host : "*", listenres->port);
2205 snew = accept(s, (struct sockaddr *)&from, &fromlen);
2207 debug(DBG_WARN, "accept failed");
2210 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2212 conf = find_conf('T', (struct sockaddr *)&from, clconfs, NULL);
2214 debug(DBG_WARN, "ignoring request, not a known TLS client");
2215 shutdown(snew, SHUT_RDWR);
2220 client = addclient(conf);
2223 debug(DBG_WARN, "Failed to create new client instance");
2224 shutdown(snew, SHUT_RDWR);
2228 client->ssl = SSL_new(client->conf->ssl_ctx);
2229 SSL_set_fd(client->ssl, snew);
2230 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
2231 debug(DBG_ERR, "tlslistener: pthread_create failed");
2232 SSL_free(client->ssl);
2233 removeclient(client);
2234 shutdown(snew, SHUT_RDWR);
2238 pthread_detach(tlsserverth);
2243 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
2246 STACK_OF(X509_NAME) *calist;
2248 unsigned long error;
2250 if (!certfile || !certkeyfile)
2251 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2253 if (!cacertfile && !cacertpath)
2254 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2257 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2258 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2259 for (i = 0; i < CRYPTO_num_locks(); i++) {
2260 ssl_lock_count[i] = 0;
2261 pthread_mutex_init(&ssl_locks[i], NULL);
2263 CRYPTO_set_id_callback(ssl_thread_id);
2264 CRYPTO_set_locking_callback(ssl_locking_callback);
2266 SSL_load_error_strings();
2269 while (!RAND_status()) {
2270 time_t t = time(NULL);
2271 pid_t pid = getpid();
2272 RAND_seed((unsigned char *)&t, sizeof(time_t));
2273 RAND_seed((unsigned char *)&pid, sizeof(pid));
2276 ctx = SSL_CTX_new(TLSv1_method());
2278 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2279 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2281 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2282 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2283 !SSL_CTX_check_private_key(ctx) ||
2284 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2285 while ((error = ERR_get_error()))
2286 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2287 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2290 calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
2291 if (!cacertfile || calist) {
2294 calist = sk_X509_NAME_new_null();
2295 if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
2296 sk_X509_NAME_free(calist);
2302 while ((error = ERR_get_error()))
2303 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2304 debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
2306 SSL_CTX_set_client_CA_list(ctx, calist);
2308 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2309 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2311 new = malloc(sizeof(struct tls));
2312 if (!new || !list_push(tlsconfs, new))
2313 debugx(1, DBG_ERR, "malloc failed");
2315 memset(new, 0, sizeof(struct tls));
2316 new->name = stringcopy(value, 0);
2318 debugx(1, DBG_ERR, "malloc failed");
2321 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2325 struct list_node *entry;
2328 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2329 t = (struct tls *)entry->data;
2333 SSL_CTX_free(t->ctx);
2335 list_destroy(tlsconfs);
2339 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2340 struct list_node *entry;
2341 struct tls *t, *t1 = NULL, *t2 = NULL;
2343 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2344 t = (struct tls *)entry->data;
2345 if (!strcasecmp(t->name, alt1)) {
2349 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2360 void addrealm(char *value, char **servers, char *message) {
2362 struct realm *realm;
2363 char *s, *regex = NULL;
2364 struct list_node *entry;
2365 struct clsrvconf *conf;
2367 if (*value == '/') {
2368 /* regexp, remove optional trailing / if present */
2369 if (value[strlen(value) - 1] == '/')
2370 value[strlen(value) - 1] = '\0';
2372 /* not a regexp, let us make it one */
2373 if (*value == '*' && !value[1])
2374 regex = stringcopy(".*", 0);
2376 for (n = 0, s = value; *s;)
2379 regex = malloc(strlen(value) + n + 3);
2382 for (n = 1, s = value; *s; s++) {
2392 debugx(1, DBG_ERR, "malloc failed");
2393 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2396 realm = malloc(sizeof(struct realm));
2398 debugx(1, DBG_ERR, "malloc failed");
2400 memset(realm, 0, sizeof(struct realm));
2401 realm->name = stringcopy(value, 0);
2403 debugx(1, DBG_ERR, "malloc failed");
2404 if (message && strlen(message) > 253)
2405 debugx(1, DBG_ERR, "ReplyMessage can be at most 253 bytes");
2406 realm->message = message;
2408 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB))
2409 debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2413 if (servers && *servers) {
2414 realm->srvconfs = list_create();
2415 if (!realm->srvconfs)
2416 debugx(1, DBG_ERR, "malloc failed");
2417 for (n = 0; servers[n]; n++) {
2418 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2419 conf = (struct clsrvconf *)entry->data;
2420 if (!strcasecmp(servers[n], conf->name))
2424 debugx(1, DBG_ERR, "addrealm failed, no server %s", servers[n]);
2425 if (!list_push(realm->srvconfs, conf))
2426 debugx(1, DBG_ERR, "malloc failed");
2427 debug(DBG_DBG, "addrealm: added server %s for realm %s", conf->name, value);
2430 realm->srvconfs = NULL;
2432 if (!list_push(realms, realm))
2433 debugx(1, DBG_ERR, "malloc failed");
2434 debug(DBG_DBG, "addrealm: added realm %s", value);
2437 struct gconffile *openconfigfile(const char *filename) {
2439 char pathname[100], *base = NULL;
2440 struct gconffile *cf = NULL;
2442 f = pushgconffile(&cf, filename);
2444 debug(DBG_DBG, "reading config file %s", filename);
2448 if (strlen(filename) + 1 <= sizeof(pathname)) {
2449 /* basename() might modify the string */
2450 strcpy(pathname, filename);
2451 base = basename(pathname);
2452 f = pushgconffile(&cf, base);
2456 debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
2458 debug(DBG_DBG, "reading config file %s", base);
2462 int addmatchcertattr(struct clsrvconf *conf, char *matchcertattr) {
2465 v = matchcertattr + 20;
2466 if (strncasecmp(matchcertattr, "SubjectAltName:URI:/", 20) || !*v)
2468 /* regexp, remove optional trailing / if present */
2469 if (v[strlen(v) - 1] == '/')
2470 v[strlen(v) - 1] = '\0';
2474 conf->certuriregex = malloc(sizeof(regex_t));
2475 if (!conf->certuriregex) {
2476 debug(DBG_ERR, "malloc failed");
2479 if (regcomp(conf->certuriregex, v, REG_ICASE | REG_NOSUB)) {
2480 free(conf->certuriregex);
2481 conf->certuriregex = NULL;
2482 debug(DBG_ERR, "failed to compile regular expression %s", v);
2488 int addrewriteattr(struct clsrvconf *conf, char *rewriteattr) {
2491 v = rewriteattr + 11;
2492 if (strncasecmp(rewriteattr, "User-Name:/", 11) || !*v)
2494 /* regexp, remove optional trailing / if present */
2495 if (v[strlen(v) - 1] == '/')
2496 v[strlen(v) - 1] = '\0';
2504 conf->rewriteattrregex = malloc(sizeof(regex_t));
2505 if (!conf->rewriteattrregex) {
2506 debug(DBG_ERR, "malloc failed");
2510 conf->rewriteattrreplacement = stringcopy(w, 0);
2511 if (!conf->rewriteattrreplacement) {
2512 free(conf->rewriteattrregex);
2513 conf->rewriteattrregex = NULL;
2517 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
2518 free(conf->rewriteattrregex);
2519 conf->rewriteattrregex = NULL;
2520 free(conf->rewriteattrreplacement);
2521 conf->rewriteattrreplacement = NULL;
2522 debug(DBG_ERR, "failed to compile regular expression %s", v);
2529 void confclient_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2530 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *rewriteattr = NULL;
2531 struct clsrvconf *conf;
2533 debug(DBG_DBG, "confclient_cb called for %s", block);
2535 conf = malloc(sizeof(struct clsrvconf));
2536 if (!conf || !list_push(clconfs, conf))
2537 debugx(1, DBG_ERR, "malloc failed");
2538 memset(conf, 0, sizeof(struct clsrvconf));
2540 getgenericconfig(cf, block,
2541 "type", CONF_STR, &type,
2542 "host", CONF_STR, &conf->host,
2543 "secret", CONF_STR, &conf->secret,
2544 "tls", CONF_STR, &tls,
2545 "matchcertificateattribute", CONF_STR, &matchcertattr,
2546 "rewriteattribute", CONF_STR, &rewriteattr,
2550 /* leave conf->name to be NULL for clients */
2552 conf->host = stringcopy(val, 0);
2554 if (type && !strcasecmp(type, "udp")) {
2557 } else if (type && !strcasecmp(type, "tls")) {
2558 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultclient", "default");
2560 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2561 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2562 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2566 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2571 free(matchcertattr);
2574 if (!addrewriteattr(conf, rewriteattr))
2575 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2579 if (!resolvepeer(conf, 0))
2580 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2582 if (!conf->secret) {
2583 if (conf->type == 'U')
2584 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2585 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2589 void confserver_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2590 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *statusserver = NULL;
2591 struct clsrvconf *conf;
2593 debug(DBG_DBG, "confserver_cb called for %s", block);
2595 conf = malloc(sizeof(struct clsrvconf));
2596 if (!conf || !list_push(srvconfs, conf))
2597 debugx(1, DBG_ERR, "malloc failed");
2598 memset(conf, 0, sizeof(struct clsrvconf));
2600 getgenericconfig(cf, block,
2601 "type", CONF_STR, &type,
2602 "host", CONF_STR, &conf->host,
2603 "port", CONF_STR, &conf->port,
2604 "secret", CONF_STR, &conf->secret,
2605 "tls", CONF_STR, &tls,
2606 "matchcertificateattribute", CONF_STR, &matchcertattr,
2607 "StatusServer", CONF_STR, &statusserver,
2611 conf->name = stringcopy(val, 0);
2613 conf->host = stringcopy(val, 0);
2615 if (type && !strcasecmp(type, "udp")) {
2619 conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
2620 } else if (type && !strcasecmp(type, "tls")) {
2621 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultserver", "default");
2623 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2624 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2625 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2627 conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
2631 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2636 free(matchcertattr);
2638 if (!resolvepeer(conf, 0))
2639 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2641 if (!conf->secret) {
2642 if (conf->type == 'U')
2643 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2644 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2648 if (!strcasecmp(statusserver, "on"))
2649 conf->statusserver = 1;
2650 else if (strcasecmp(statusserver, "off"))
2651 debugx(1, DBG_ERR, "error in block %s, StatusServer is %s, must be on or off", block, statusserver);
2656 void confrealm_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2657 char **servers = NULL, *msg = NULL;
2659 debug(DBG_DBG, "confrealm_cb called for %s", block);
2661 getgenericconfig(cf, block,
2662 "server", CONF_MSTR, &servers,
2663 "ReplyMessage", CONF_STR, &msg,
2667 addrealm(val, servers, msg);
2671 void conftls_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2672 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
2674 debug(DBG_DBG, "conftls_cb called for %s", block);
2676 getgenericconfig(cf, block,
2677 "CACertificateFile", CONF_STR, &cacertfile,
2678 "CACertificatePath", CONF_STR, &cacertpath,
2679 "CertificateFile", CONF_STR, &certfile,
2680 "CertificateKeyFile", CONF_STR, &certkeyfile,
2681 "CertificateKeyPassword", CONF_STR, &certkeypwd,
2685 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
2693 void getmainconfig(const char *configfile) {
2694 char *loglevel = NULL;
2695 struct gconffile *cfs;
2697 cfs = openconfigfile(configfile);
2698 memset(&options, 0, sizeof(options));
2700 clconfs = list_create();
2702 debugx(1, DBG_ERR, "malloc failed");
2704 srvconfs = list_create();
2706 debugx(1, DBG_ERR, "malloc failed");
2708 realms = list_create();
2710 debugx(1, DBG_ERR, "malloc failed");
2712 tlsconfs = list_create();
2714 debugx(1, DBG_ERR, "malloc failed");
2716 getgenericconfig(&cfs, NULL,
2717 "ListenUDP", CONF_STR, &options.listenudp,
2718 "ListenTCP", CONF_STR, &options.listentcp,
2719 "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
2720 "SourceUDP", CONF_STR, &options.sourceudp,
2721 "SourceTCP", CONF_STR, &options.sourcetcp,
2722 "LogLevel", CONF_STR, &loglevel,
2723 "LogDestination", CONF_STR, &options.logdestination,
2724 "Client", CONF_CBK, confclient_cb,
2725 "Server", CONF_CBK, confserver_cb,
2726 "Realm", CONF_CBK, confrealm_cb,
2727 "TLS", CONF_CBK, conftls_cb,
2734 if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
2735 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
2736 options.loglevel = *loglevel - '0';
2741 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
2744 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
2747 *configfile = optarg;
2750 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
2751 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
2752 *loglevel = *optarg - '0';
2761 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
2766 if (!(argc - optind))
2770 debug(DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
2775 int daemon(int a, int b) {
2783 for (i = 0; i < 3; i++) {
2785 open("/dev/null", O_RDWR);
2791 int main(int argc, char **argv) {
2792 pthread_t udpserverth, udpaccserverth, udpclient4rdth, udpclient6rdth;
2793 struct list_node *entry;
2794 uint8_t foreground = 0, pretend = 0, loglevel = 0;
2795 char *configfile = NULL;
2797 debug_init("radsecproxy");
2798 debug_set_level(DEBUG_LEVEL);
2799 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
2801 debug_set_level(loglevel);
2802 getmainconfig(configfile ? configfile : CONFIG_MAIN);
2804 options.loglevel = loglevel;
2805 else if (options.loglevel)
2806 debug_set_level(options.loglevel);
2808 options.logdestination = NULL;
2810 if (!options.logdestination)
2811 options.logdestination = "x-syslog:///";
2812 debug_set_destination(options.logdestination);
2816 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
2818 if (!list_first(clconfs))
2819 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
2820 if (!list_first(srvconfs))
2821 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
2822 if (!list_first(realms))
2823 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
2825 if (!foreground && (daemon(0, 0) < 0))
2826 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
2828 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
2830 if (client_udp_count) {
2831 udp_server_replyq = newreplyq();
2832 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
2833 debugx(1, DBG_ERR, "pthread_create failed");
2834 if (options.listenaccudp)
2835 if (pthread_create(&udpaccserverth, NULL, udpaccserverrd, NULL))
2836 debugx(1, DBG_ERR, "pthread_create failed");
2839 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2840 addserver((struct clsrvconf *)entry->data);
2841 if (pthread_create(&((struct clsrvconf *)entry->data)->servers->clientth, NULL, clientwr,
2842 (void *)((struct clsrvconf *)entry->data)->servers))
2843 debugx(1, DBG_ERR, "pthread_create failed");
2845 /* srcudpres no longer needed, while srctcpres is needed later */
2850 if (udp_client4_sock >= 0)
2851 if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
2852 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
2853 if (udp_client6_sock >= 0)
2854 if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
2855 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
2857 if (client_tls_count)
2858 return tlslistener();
2860 /* just hang around doing nothing, anything to do here? */