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>
53 #include "radsecproxy.h"
55 static struct options options;
56 struct list *clconfs, *srvconfs, *realms, *tlsconfs;
58 static int client_udp_count = 0;
59 static int client_tls_count = 0;
60 static int server_udp_count = 0;
61 static int server_tls_count = 0;
63 static struct clsrvconf *srcudpres = NULL;
64 static struct clsrvconf *srctcpres = NULL;
66 static struct replyq *udp_server_replyq = NULL;
67 static int udp_server_sock = -1;
68 static int udp_accserver_sock = -1;
69 static int udp_client4_sock = -1;
70 static int udp_client6_sock = -1;
71 static pthread_mutex_t *ssl_locks;
72 static long *ssl_lock_count;
76 /* callbacks for making OpenSSL thread safe */
77 unsigned long ssl_thread_id() {
78 return (unsigned long)pthread_self();
81 void ssl_locking_callback(int mode, int type, const char *file, int line) {
82 if (mode & CRYPTO_LOCK) {
83 pthread_mutex_lock(&ssl_locks[type]);
84 ssl_lock_count[type]++;
86 pthread_mutex_unlock(&ssl_locks[type]);
89 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
90 int pwdlen = strlen(userdata);
91 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
93 memcpy(buf, userdata, pwdlen);
97 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
102 err_cert = X509_STORE_CTX_get_current_cert(ctx);
103 err = X509_STORE_CTX_get_error(ctx);
104 depth = X509_STORE_CTX_get_error_depth(ctx);
106 if (depth > MAX_CERT_DEPTH) {
108 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
109 X509_STORE_CTX_set_error(ctx, err);
113 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
114 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
117 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
118 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
119 debug(DBG_WARN, "\tIssuer=%s", buf);
121 case X509_V_ERR_CERT_NOT_YET_VALID:
122 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
123 debug(DBG_WARN, "\tCertificate not yet valid");
125 case X509_V_ERR_CERT_HAS_EXPIRED:
126 debug(DBG_WARN, "Certificate has expired");
128 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
129 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
134 printf("certificate verify returns %d\n", ok);
139 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
140 struct addrinfo hints, *addrinfo, *res;
144 slash = conf->host ? strchr(conf->host, '/') : NULL;
148 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
152 if (*s < '0' || *s > '9') {
153 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
156 plen = atoi(slash + 1);
157 if (plen < 0 || plen > 128) {
158 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
163 memset(&hints, 0, sizeof(hints));
164 hints.ai_socktype = (conf->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
165 hints.ai_family = AF_UNSPEC;
166 hints.ai_flags = ai_flags;
167 if (!conf->host && !conf->port) {
168 /* getaddrinfo() doesn't like host and port to be NULL */
169 if (getaddrinfo(conf->host, DEFAULT_UDP_PORT, &hints, &addrinfo)) {
170 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
173 for (res = addrinfo; res; res = res->ai_next) {
174 switch (res->ai_family) {
176 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
179 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
185 hints.ai_flags |= AI_NUMERICHOST;
186 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
187 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host, conf->port);
192 switch (addrinfo->ai_family) {
195 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
196 freeaddrinfo(addrinfo);
203 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
204 freeaddrinfo(addrinfo);
207 conf->prefixlen = plen;
209 conf->prefixlen = 255;
212 freeaddrinfo(conf->addrinfo);
213 conf->addrinfo = addrinfo;
217 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
219 struct addrinfo *res;
221 for (res = addrinfo; res; res = res->ai_next) {
222 if (family != AF_UNSPEC && family != res->ai_family)
224 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
226 debug(DBG_WARN, "bindtoaddr: socket failed");
230 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
233 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
236 if (!bind(s, res->ai_addr, res->ai_addrlen))
238 debug(DBG_WARN, "bindtoaddr: bind failed");
244 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
249 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
253 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
255 debugx(1, DBG_ERR, "no ] matching initial [");
259 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
262 debugx(1, DBG_ERR, "missing host/address");
264 conf->host = stringcopy(field, p - field);
267 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
268 debugx(1, DBG_ERR, "unexpected character after ]");
271 /* port number or service name is specified */;
273 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
275 debugx(1, DBG_ERR, "syntax error, : but no following port");
276 conf->port = stringcopy(field, p - field);
278 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
282 struct clsrvconf *resolve_hostport(char type, char *lconf, char *default_port) {
283 struct clsrvconf *conf;
285 conf = malloc(sizeof(struct clsrvconf));
287 debugx(1, DBG_ERR, "malloc failed");
288 memset(conf, 0, sizeof(struct clsrvconf));
291 parsehostport(lconf, conf, default_port);
292 if (!strcmp(conf->host, "*")) {
297 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
298 if (!resolvepeer(conf, AI_PASSIVE))
299 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
303 int connecttcp(struct addrinfo *addrinfo) {
305 struct addrinfo *res;
308 for (res = addrinfo; res; res = res->ai_next) {
309 s = bindtoaddr(srctcpres->addrinfo, res->ai_family, 1, 1);
311 debug(DBG_WARN, "connecttoserver: socket failed");
314 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
316 debug(DBG_WARN, "connecttoserver: connect failed");
323 /* returns 1 if the len first bits are equal, else 0 */
324 int prefixmatch(void *a1, void *a2, uint8_t len) {
325 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
327 if (l && memcmp(a1, a2, l))
332 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
335 /* returns the config with matching address, or NULL */
336 /* if conf argument is not NULL, we only check that one */
337 struct clsrvconf *find_conf(char type, struct sockaddr *addr, struct list *confs, struct clsrvconf *conf) {
338 struct sockaddr_in6 *sa6 = NULL;
339 struct in_addr *a4 = NULL;
340 struct addrinfo *res;
341 struct list_node *entry;
343 if (addr->sa_family == AF_INET6) {
344 sa6 = (struct sockaddr_in6 *)addr;
345 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
346 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
350 a4 = &((struct sockaddr_in *)addr)->sin_addr;
353 if (conf->type == type) {
354 if (conf->prefixlen == 255) {
355 for (res = conf->addrinfo; res; res = res->ai_next)
356 if ((a4 && res->ai_family == AF_INET &&
357 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
358 (sa6 && res->ai_family == AF_INET6 &&
359 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
362 res = conf->addrinfo;
364 ((a4 && res->ai_family == AF_INET &&
365 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
366 (sa6 && res->ai_family == AF_INET6 &&
367 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
374 for (entry = list_first(confs); entry; entry = list_next(entry)) {
375 conf = (struct clsrvconf *)entry->data;
376 if (conf->type == type) {
377 if (conf->prefixlen == 255) {
378 for (res = conf->addrinfo; res; res = res->ai_next)
379 if ((a4 && res->ai_family == AF_INET &&
380 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
381 (sa6 && res->ai_family == AF_INET6 &&
382 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
385 res = conf->addrinfo;
387 ((a4 && res->ai_family == AF_INET &&
388 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
389 (sa6 && res->ai_family == AF_INET6 &&
390 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
398 struct replyq *newreplyq() {
399 struct replyq *replyq;
401 replyq = malloc(sizeof(struct replyq));
403 debugx(1, DBG_ERR, "malloc failed");
404 replyq->replies = list_create();
405 if (!replyq->replies)
406 debugx(1, DBG_ERR, "malloc failed");
407 pthread_mutex_init(&replyq->mutex, NULL);
408 pthread_cond_init(&replyq->cond, NULL);
412 struct client *addclient(struct clsrvconf *conf) {
413 struct client *new = malloc(sizeof(struct client));
416 debug(DBG_ERR, "malloc failed");
419 if (!conf->clients) {
420 conf->clients = list_create();
421 if (!conf->clients) {
422 debug(DBG_ERR, "malloc failed");
427 memset(new, 0, sizeof(struct client));
429 new->replyq = conf->type == 'T' ? newreplyq() : udp_server_replyq;
431 list_push(conf->clients, new);
435 void removeclient(struct client *client) {
436 if (!client || !client->conf->clients)
439 list_removedata(client->conf->clients, client);
443 void addserver(struct clsrvconf *conf) {
445 debugx(1, DBG_ERR, "addserver: currently works with just one server per conf");
447 conf->servers = malloc(sizeof(struct server));
449 debugx(1, DBG_ERR, "malloc failed");
450 memset(conf->servers, 0, sizeof(struct server));
451 conf->servers->conf = conf;
453 if (conf->type == 'U') {
455 srcudpres = resolve_hostport('U', options.sourceudp, NULL);
456 switch (conf->addrinfo->ai_family) {
458 if (udp_client4_sock < 0) {
459 udp_client4_sock = bindtoaddr(srcudpres->addrinfo, AF_INET, 0, 1);
460 if (udp_client4_sock < 0)
461 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
463 conf->servers->sock = udp_client4_sock;
466 if (udp_client6_sock < 0) {
467 udp_client6_sock = bindtoaddr(srcudpres->addrinfo, AF_INET6, 0, 1);
468 if (udp_client6_sock < 0)
469 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
471 conf->servers->sock = udp_client6_sock;
474 debugx(1, DBG_ERR, "addserver: unsupported address family");
479 srctcpres = resolve_hostport('T', options.sourcetcp, NULL);
480 conf->servers->sock = -1;
483 pthread_mutex_init(&conf->servers->lock, NULL);
484 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
485 if (!conf->servers->requests)
486 debugx(1, DBG_ERR, "malloc failed");
487 conf->servers->newrq = 0;
488 pthread_mutex_init(&conf->servers->newrq_mutex, NULL);
489 pthread_cond_init(&conf->servers->newrq_cond, NULL);
492 /* exactly one of client and server must be non-NULL */
493 /* should probably take peer list (client(s) or server(s)) as argument instead */
494 /* if *peer == NULL we return who we received from, else require it to be from peer */
495 /* return from in sa if not NULL */
496 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
498 unsigned char buf[65536], *rad;
499 struct sockaddr_storage from;
500 socklen_t fromlen = sizeof(from);
502 struct list_node *node;
505 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
507 debug(DBG_WARN, "radudpget: recv failed");
510 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
513 debug(DBG_WARN, "radudpget: packet too small");
519 debug(DBG_WARN, "radudpget: length too small");
524 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
528 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
532 p = find_conf('U', (struct sockaddr *)&from, NULL, (*client)->conf);
534 p = find_conf('U', (struct sockaddr *)&from, clconfs, NULL);
537 p = find_conf('U', (struct sockaddr *)&from, NULL, (*server)->conf);
539 p = find_conf('U', (struct sockaddr *)&from, srvconfs, NULL);
542 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer, ignoring");
548 debug(DBG_ERR, "radudpget: malloc failed");
552 if (client && !*client) {
553 node = list_first(p->clients);
554 *client = node ? (struct client *)node->data : addclient(p);
559 } else if (server && !*server)
560 *server = p->servers;
564 memcpy(rad, buf, len);
570 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
571 int loc, i, l, n, r = 0;
574 STACK_OF(GENERAL_NAME) *alt;
577 debug(DBG_DBG, "subjectaltnameaddr");
579 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
583 ex = X509_get_ext(cert, loc);
584 alt = X509V3_EXT_d2i(ex);
588 n = sk_GENERAL_NAME_num(alt);
589 for (i = 0; i < n; i++) {
590 gn = sk_GENERAL_NAME_value(alt, i);
591 if (gn->type != GEN_IPADD)
594 v = (char *)ASN1_STRING_data(gn->d.ia5);
595 l = ASN1_STRING_length(gn->d.ia5);
596 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
597 && !memcmp(v, &addr, l)) {
602 GENERAL_NAMES_free(alt);
606 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
607 int loc, i, l, n, r = 0;
610 STACK_OF(GENERAL_NAME) *alt;
613 debug(DBG_DBG, "subjectaltnameregexp");
615 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
619 ex = X509_get_ext(cert, loc);
620 alt = X509V3_EXT_d2i(ex);
624 n = sk_GENERAL_NAME_num(alt);
625 for (i = 0; i < n; i++) {
626 gn = sk_GENERAL_NAME_value(alt, i);
627 if (gn->type != type)
630 v = (char *)ASN1_STRING_data(gn->d.ia5);
631 l = ASN1_STRING_length(gn->d.ia5);
635 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
638 if (memcmp(v, exact, l))
641 s = stringcopy((char *)v, l);
643 debug(DBG_ERR, "malloc failed");
646 if (regexec(regex, s, 0, NULL, 0)) {
655 GENERAL_NAMES_free(alt);
659 int tlsverifycert(SSL *ssl, struct clsrvconf *conf) {
666 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
668 struct in6_addr addr;
670 if (SSL_get_verify_result(ssl) != X509_V_OK) {
671 debug(DBG_ERR, "tlsverifycert: basic validation failed");
672 while ((error = ERR_get_error()))
673 debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
677 cert = SSL_get_peer_certificate(ssl);
679 debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
683 if (conf->prefixlen == 255) {
684 if (inet_pton(AF_INET, conf->host, &addr))
686 else if (inet_pton(AF_INET6, conf->host, &addr))
689 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
693 debug(DBG_DBG, "tlsverifycert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
696 debug(DBG_DBG, "tlsverifycert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
698 nm = X509_get_subject_name(cert);
701 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
704 e = X509_NAME_get_entry(nm, loc);
705 s = X509_NAME_ENTRY_get_data(e);
706 v = (char *) ASN1_STRING_data(s);
707 l = ASN1_STRING_length(s);
711 printfchars(NULL, "cn", NULL, v, l);
713 if (l == strlen(conf->host) && !strncasecmp(conf->host, v, l)) {
715 debug(DBG_DBG, "tlsverifycert: Found cn matching host %s", conf->host);
721 debug(DBG_ERR, "tlsverifycert: cn not matching host %s", conf->host);
726 if (conf->certuriregex) {
727 r = subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex);
729 debug(DBG_DBG, "tlsverifycert: subjectaltname URI not matching regex");
733 debug(DBG_DBG, "tlsverifycert: subjectaltname URI matching regex");
739 void tlsconnect(struct server *server, struct timeval *when, char *text) {
743 debug(DBG_DBG, "tlsconnect called from %s", text);
744 pthread_mutex_lock(&server->lock);
745 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
746 /* already reconnected, nothing to do */
747 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
748 pthread_mutex_unlock(&server->lock);
752 debug(DBG_DBG, "tlsconnect %s", text);
755 gettimeofday(&now, NULL);
756 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
757 if (server->connectionok) {
758 server->connectionok = 0;
760 } else if (elapsed < 5)
762 else if (elapsed < 300) {
763 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
765 } else if (elapsed < 100000) {
766 debug(DBG_INFO, "tlsconnect: sleeping %ds", 600);
769 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
770 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
771 if (server->sock >= 0)
773 if ((server->sock = connecttcp(server->conf->addrinfo)) < 0) {
774 debug(DBG_ERR, "tlsconnect: connecttcp failed");
778 SSL_free(server->ssl);
779 server->ssl = SSL_new(server->conf->ssl_ctx);
780 SSL_set_fd(server->ssl, server->sock);
781 if (SSL_connect(server->ssl) > 0 && tlsverifycert(server->ssl, server->conf))
784 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
785 gettimeofday(&server->lastconnecttry, NULL);
786 pthread_mutex_unlock(&server->lock);
789 unsigned char *radtlsget(SSL *ssl) {
791 unsigned char buf[4], *rad;
794 for (total = 0; total < 4; total += cnt) {
795 cnt = SSL_read(ssl, buf + total, 4 - total);
797 debug(DBG_ERR, "radtlsget: connection lost");
798 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
799 /* remote end sent close_notify, send one back */
809 debug(DBG_ERR, "radtlsget: malloc failed");
814 for (; total < len; total += cnt) {
815 cnt = SSL_read(ssl, rad + total, len - total);
817 debug(DBG_ERR, "radtlsget: connection lost");
818 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
819 /* remote end sent close_notify, send one back */
831 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
834 debug(DBG_DBG, "radtlsget: got %d bytes", total);
838 int clientradput(struct server *server, unsigned char *rad) {
842 struct timeval lastconnecttry;
843 struct clsrvconf *conf = server->conf;
846 if (conf->type == 'U') {
847 if (sendto(server->sock, rad, len, 0, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen) >= 0) {
848 debug(DBG_DBG, "clienradput: sent UDP of length %d to %s port %s", len, conf->host, conf->port);
851 debug(DBG_WARN, "clientradput: send failed");
855 lastconnecttry = server->lastconnecttry;
856 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
857 while ((error = ERR_get_error()))
858 debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
859 tlsconnect(server, &lastconnecttry, "clientradput");
860 lastconnecttry = server->lastconnecttry;
863 server->connectionok = 1;
864 debug(DBG_DBG, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
868 int radsign(unsigned char *rad, unsigned char *sec) {
869 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
870 static unsigned char first = 1;
871 static EVP_MD_CTX mdctx;
875 pthread_mutex_lock(&lock);
877 EVP_MD_CTX_init(&mdctx);
881 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
882 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
883 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
884 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
886 pthread_mutex_unlock(&lock);
890 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
891 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
892 static unsigned char first = 1;
893 static EVP_MD_CTX mdctx;
894 unsigned char hash[EVP_MAX_MD_SIZE];
898 pthread_mutex_lock(&lock);
900 EVP_MD_CTX_init(&mdctx);
906 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
907 EVP_DigestUpdate(&mdctx, rad, 4) &&
908 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
909 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
910 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
911 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
913 !memcmp(hash, rad + 4, 16));
914 pthread_mutex_unlock(&lock);
918 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
919 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
920 static unsigned char first = 1;
921 static HMAC_CTX hmacctx;
923 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
925 pthread_mutex_lock(&lock);
927 HMAC_CTX_init(&hmacctx);
931 memcpy(auth, authattr, 16);
932 memset(authattr, 0, 16);
934 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
935 HMAC_Update(&hmacctx, rad, RADLEN(rad));
936 HMAC_Final(&hmacctx, hash, &md_len);
937 memcpy(authattr, auth, 16);
939 debug(DBG_WARN, "message auth computation failed");
940 pthread_mutex_unlock(&lock);
944 if (memcmp(auth, hash, 16)) {
945 debug(DBG_WARN, "message authenticator, wrong value");
946 pthread_mutex_unlock(&lock);
950 pthread_mutex_unlock(&lock);
954 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
955 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
956 static unsigned char first = 1;
957 static HMAC_CTX hmacctx;
963 pthread_mutex_lock(&lock);
965 HMAC_CTX_init(&hmacctx);
969 memset(authattrval, 0, 16);
971 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
972 HMAC_Update(&hmacctx, rad, RADLEN(rad));
973 HMAC_Final(&hmacctx, authattrval, &md_len);
975 debug(DBG_WARN, "message auth computation failed");
976 pthread_mutex_unlock(&lock);
980 pthread_mutex_unlock(&lock);
984 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
986 if (ATTRTYPE(attrs) == type)
988 length -= ATTRLEN(attrs);
989 attrs += ATTRLEN(attrs);
994 void freerqdata(struct request *rq) {
995 if (rq->origusername)
996 free(rq->origusername);
1001 void sendrq(struct server *to, struct request *rq) {
1005 pthread_mutex_lock(&to->newrq_mutex);
1006 /* might simplify if only try nextid, might be ok */
1007 for (i = to->nextid; i < MAX_REQUESTS; i++)
1008 if (!to->requests[i].buf)
1010 if (i == MAX_REQUESTS) {
1011 for (i = 0; i < to->nextid; i++)
1012 if (!to->requests[i].buf)
1014 if (i == to->nextid) {
1015 debug(DBG_WARN, "No room in queue, dropping request");
1017 pthread_mutex_unlock(&to->newrq_mutex);
1022 rq->buf[1] = (char)i;
1024 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1025 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1027 pthread_mutex_unlock(&to->newrq_mutex);
1031 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1032 to->requests[i] = *rq;
1037 debug(DBG_DBG, "signalling client writer");
1038 pthread_cond_signal(&to->newrq_cond);
1040 pthread_mutex_unlock(&to->newrq_mutex);
1043 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
1044 struct reply *reply;
1047 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1049 debug(DBG_WARN, "sendreply: failed to sign message");
1053 reply = malloc(sizeof(struct reply));
1056 debug(DBG_ERR, "sendreply: malloc failed");
1059 memset(reply, 0, sizeof(struct reply));
1062 reply->tosa = *tosa;
1064 pthread_mutex_lock(&to->replyq->mutex);
1066 first = list_first(to->replyq->replies) == NULL;
1068 if (!list_push(to->replyq->replies, reply)) {
1069 pthread_mutex_unlock(&to->replyq->mutex);
1072 debug(DBG_ERR, "sendreply: malloc failed");
1077 debug(DBG_DBG, "signalling server writer");
1078 pthread_cond_signal(&to->replyq->cond);
1080 pthread_mutex_unlock(&to->replyq->mutex);
1083 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1084 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1085 static unsigned char first = 1;
1086 static EVP_MD_CTX mdctx;
1087 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1088 unsigned int md_len;
1089 uint8_t i, offset = 0, out[128];
1091 pthread_mutex_lock(&lock);
1093 EVP_MD_CTX_init(&mdctx);
1099 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1100 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1101 !EVP_DigestUpdate(&mdctx, input, 16) ||
1102 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1104 pthread_mutex_unlock(&lock);
1107 for (i = 0; i < 16; i++)
1108 out[offset + i] = hash[i] ^ in[offset + i];
1109 input = out + offset - 16;
1114 memcpy(in, out, len);
1115 pthread_mutex_unlock(&lock);
1119 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1120 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1121 static unsigned char first = 1;
1122 static EVP_MD_CTX mdctx;
1123 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1124 unsigned int md_len;
1125 uint8_t i, offset = 0, out[128];
1127 pthread_mutex_lock(&lock);
1129 EVP_MD_CTX_init(&mdctx);
1135 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1136 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1137 !EVP_DigestUpdate(&mdctx, input, 16) ||
1138 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1140 pthread_mutex_unlock(&lock);
1143 for (i = 0; i < 16; i++)
1144 out[offset + i] = hash[i] ^ in[offset + i];
1145 input = in + offset;
1150 memcpy(in, out, len);
1151 pthread_mutex_unlock(&lock);
1155 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1156 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1157 static unsigned char first = 1;
1158 static EVP_MD_CTX mdctx;
1159 unsigned char hash[EVP_MAX_MD_SIZE];
1160 unsigned int md_len;
1163 pthread_mutex_lock(&lock);
1165 EVP_MD_CTX_init(&mdctx);
1170 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1171 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1172 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1175 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1176 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1177 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1178 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1179 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1180 pthread_mutex_unlock(&lock);
1185 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1188 for (i = 0; i < 16; i++)
1191 for (offset = 16; offset < len; offset += 16) {
1193 printf("text + offset - 16 c(%d): ", offset / 16);
1194 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1196 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1197 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1198 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1199 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1201 pthread_mutex_unlock(&lock);
1205 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1208 for (i = 0; i < 16; i++)
1209 text[offset + i] ^= hash[i];
1213 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1216 pthread_mutex_unlock(&lock);
1220 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1221 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1222 static unsigned char first = 1;
1223 static EVP_MD_CTX mdctx;
1224 unsigned char hash[EVP_MAX_MD_SIZE];
1225 unsigned int md_len;
1229 pthread_mutex_lock(&lock);
1231 EVP_MD_CTX_init(&mdctx);
1236 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1237 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1238 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1241 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1242 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1243 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1244 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1245 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1246 pthread_mutex_unlock(&lock);
1251 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1254 for (i = 0; i < 16; i++)
1255 plain[i] = text[i] ^ hash[i];
1257 for (offset = 16; offset < len; offset += 16) {
1259 printf("text + offset - 16 c(%d): ", offset / 16);
1260 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1262 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1263 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1264 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1265 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1267 pthread_mutex_unlock(&lock);
1271 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1274 for (i = 0; i < 16; i++)
1275 plain[offset + i] = text[offset + i] ^ hash[i];
1278 memcpy(text, plain, len);
1280 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1283 pthread_mutex_unlock(&lock);
1287 struct realm *id2realm(char *id, uint8_t len) {
1288 struct list_node *entry;
1289 struct realm *realm;
1291 for (entry = list_first(realms); entry; entry = list_next(entry)) {
1292 realm = (struct realm *)entry->data;
1293 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1294 debug(DBG_DBG, "found matching realm: %s", realm->name);
1301 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
1304 pthread_mutex_lock(&to->newrq_mutex);
1305 for (i = 0; i < MAX_REQUESTS; i++)
1306 if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
1308 pthread_mutex_unlock(&to->newrq_mutex);
1310 return i < MAX_REQUESTS;
1313 int attrvalidate(unsigned char *attrs, int length) {
1314 while (length > 1) {
1315 if (ATTRLEN(attrs) < 2) {
1316 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1319 length -= ATTRLEN(attrs);
1321 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1324 attrs += ATTRLEN(attrs);
1327 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1331 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1332 if (len < 16 || len > 128 || len % 16) {
1333 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1337 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1338 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1342 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1344 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1345 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1351 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1354 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1355 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1358 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1359 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1365 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1366 char *oldsecret, char *newsecret) {
1367 unsigned char *attr;
1369 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1370 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1371 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1377 /* returns a pointer to the resized attribute value */
1378 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1379 uint8_t *attrs, *attr, vallen;
1383 len = RADLEN(*buf) - 20;
1386 attr = attrget(attrs, len, type);
1390 vallen = ATTRVALLEN(attr);
1391 if (vallen == newvallen)
1394 len += newvallen - vallen;
1395 if (newvallen > vallen) {
1396 new = realloc(*buf, len);
1398 debug(DBG_ERR, "resizeattr: malloc failed");
1407 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1408 attr[1] = newvallen + 2;
1409 ((uint16_t *)*buf)[1] = htons(len + 20);
1413 int rewriteusername(struct request *rq, char *in) {
1414 size_t nmatch = 10, reslen = 0, start = 0;
1415 regmatch_t pmatch[10], *pfield;
1417 unsigned char *result;
1418 char *out = rq->from->conf->rewriteattrreplacement;
1420 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1421 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1425 rq->origusername = stringcopy(in, 0);
1426 if (!rq->origusername)
1429 for (i = start; out[i]; i++) {
1430 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1431 pfield = &pmatch[out[i + 1] - '0'];
1432 if (pfield->rm_so >= 0) {
1433 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1439 reslen += i - start;
1441 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1447 for (i = start; out[i]; i++) {
1448 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1449 pfield = &pmatch[out[i + 1] - '0'];
1450 if (pfield->rm_so >= 0) {
1451 memcpy(result + reslen, out + start, i - start);
1452 reslen += i - start;
1453 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1454 reslen += pfield->rm_eo - pfield->rm_so;
1461 memcpy(result + reslen, out + start, i - start);
1462 reslen += i - start;
1463 memcpy(in, result, reslen);
1468 void acclog(unsigned char *attrs, int length, char *host) {
1469 unsigned char *attr;
1472 attr = attrget(attrs, length, RAD_Attr_User_Name);
1474 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1477 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1478 username[ATTRVALLEN(attr)] = '\0';
1479 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1482 void respondaccounting(struct request *rq) {
1483 unsigned char *resp;
1487 debug(DBG_ERR, "respondstatusserver: malloc failed");
1490 memcpy(resp, rq->buf, 20);
1491 resp[0] = RAD_Accounting_Response;
1494 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1495 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1498 void respondstatusserver(struct request *rq) {
1499 unsigned char *resp;
1503 debug(DBG_ERR, "respondstatusserver: malloc failed");
1506 memcpy(resp, rq->buf, 20);
1507 resp[0] = RAD_Access_Accept;
1510 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1511 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1514 void respondreject(struct request *rq, char *message) {
1515 unsigned char *resp;
1518 if (message && *message)
1519 len += 2 + strlen(message);
1523 debug(DBG_ERR, "respondreject: malloc failed");
1526 memcpy(resp, rq->buf, 20);
1527 resp[0] = RAD_Access_Reject;
1528 *(uint16_t *)(resp + 2) = htons(len);
1529 if (message && *message) {
1530 resp[20] = RAD_Attr_Reply_Message;
1531 resp[21] = len - 20;
1532 memcpy(resp + 22, message, len - 22);
1534 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1537 struct server *realm2server(struct realm *realm) {
1538 struct list_node *entry;
1539 struct server *server, *best = NULL;
1541 for (entry = list_first(realm->srvconfs); entry; entry = list_next(entry)) {
1542 server = ((struct clsrvconf *)entry->data)->servers;
1543 if (!server->connectionok)
1545 if (!server->loststatsrv)
1551 if (server->loststatsrv < best->loststatsrv)
1557 void radsrv(struct request *rq) {
1558 uint8_t code, id, *auth, *attrs, *attr;
1560 struct server *to = NULL;
1562 unsigned char newauth[16];
1563 struct realm *realm = NULL;
1565 code = *(uint8_t *)rq->buf;
1566 id = *(uint8_t *)(rq->buf + 1);
1567 len = RADLEN(rq->buf);
1568 auth = (uint8_t *)(rq->buf + 4);
1570 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1572 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1573 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1579 attrs = rq->buf + 20;
1581 if (!attrvalidate(attrs, len)) {
1582 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1587 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1588 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
1589 debug(DBG_WARN, "radsrv: message authentication failed");
1594 if (code != RAD_Access_Request) {
1596 case RAD_Accounting_Request:
1597 acclog(attrs, len, rq->from->conf->host);
1598 respondaccounting(rq);
1600 case RAD_Status_Server:
1601 respondstatusserver(rq);
1608 /* code == RAD_Access_Request */
1609 attr = attrget(attrs, len, RAD_Attr_User_Name);
1611 debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1615 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1616 username[ATTRVALLEN(attr)] = '\0';
1618 if (rq->from->conf->rewriteattrregex) {
1619 if (!rewriteusername(rq, username)) {
1620 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1624 len = RADLEN(rq->buf) - 20;
1625 auth = (uint8_t *)(rq->buf + 4);
1626 attrs = rq->buf + 20;
1629 if (rq->origusername)
1630 debug(DBG_DBG, "Access Request with username: %s (originally %s)", username, rq->origusername);
1632 debug(DBG_DBG, "Access Request with username: %s", username);
1634 realm = id2realm(username, strlen(username));
1636 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1641 to = realm2server(realm);
1642 if (to && rqinqueue(to, rq->from, id)) {
1643 debug(DBG_INFO, "radsrv: already got request from host %s with id %d, ignoring", rq->from->conf->host, id);
1649 if (realm->message) {
1650 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, username);
1651 respondreject(rq, realm->message);
1657 if (!RAND_bytes(newauth, 16)) {
1658 debug(DBG_WARN, "radsrv: failed to generate random auth");
1664 printfchars(NULL, "auth", "%02x ", auth, 16);
1667 attr = attrget(attrs, len, RAD_Attr_User_Password);
1669 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1670 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1676 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1678 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1679 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1686 memcpy(rq->origauth, auth, 16);
1687 memcpy(auth, newauth, 16);
1691 int replyh(struct server *server, unsigned char *buf) {
1692 struct client *from;
1695 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
1696 struct sockaddr_storage fromsa;
1699 server->connectionok = 1;
1700 server->loststatsrv = 0;
1702 i = buf[1]; /* i is the id */
1705 case RAD_Access_Accept:
1706 debug(DBG_DBG, "got Access Accept with id %d", i);
1708 case RAD_Access_Reject:
1709 debug(DBG_DBG, "got Access Reject with id %d", i);
1711 case RAD_Access_Challenge:
1712 debug(DBG_DBG, "got Access Challenge with id %d", i);
1715 debug(DBG_INFO, "replyh: discarding, only accept access accept, access reject and access challenge messages");
1719 rq = server->requests + i;
1721 pthread_mutex_lock(&server->newrq_mutex);
1722 if (!rq->buf || !rq->tries) {
1723 pthread_mutex_unlock(&server->newrq_mutex);
1724 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
1729 pthread_mutex_unlock(&server->newrq_mutex);
1730 debug(DBG_INFO, "replyh: already received, ignoring reply");
1734 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
1735 pthread_mutex_unlock(&server->newrq_mutex);
1736 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
1741 len = RADLEN(buf) - 20;
1744 if (!attrvalidate(attrs, len)) {
1745 pthread_mutex_unlock(&server->newrq_mutex);
1746 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
1750 /* Message Authenticator */
1751 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1753 if (ATTRVALLEN(messageauth) != 16) {
1754 pthread_mutex_unlock(&server->newrq_mutex);
1755 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
1758 memcpy(tmp, buf + 4, 16);
1759 memcpy(buf + 4, rq->buf + 4, 16);
1760 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
1761 pthread_mutex_unlock(&server->newrq_mutex);
1762 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
1765 memcpy(buf + 4, tmp, 16);
1766 debug(DBG_DBG, "replyh: message auth ok");
1769 if (*rq->buf == RAD_Status_Server) {
1771 pthread_mutex_unlock(&server->newrq_mutex);
1772 debug(DBG_INFO, "replyh: got status server response from %s", server->conf->host);
1777 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1778 if (ATTRVALLEN(attr) <= 4)
1781 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
1784 sublen = ATTRVALLEN(attr) - 4;
1785 subattrs = ATTRVAL(attr) + 4;
1786 if (!attrvalidate(subattrs, sublen) ||
1787 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1788 rq, server->conf->secret, from->conf->secret) ||
1789 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1790 rq, server->conf->secret, from->conf->secret))
1794 pthread_mutex_unlock(&server->newrq_mutex);
1795 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1799 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject) {
1800 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
1801 /* we know the attribute exists */
1802 memcpy(tmp, ATTRVAL(attr), ATTRVALLEN(attr));
1803 tmp[ATTRVALLEN(attr)] = '\0';
1805 case RAD_Access_Accept:
1806 if (rq->origusername)
1807 debug(DBG_INFO, "Access Accept for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1809 debug(DBG_INFO, "Access Accept for %s from %s", tmp, server->conf->host);
1811 case RAD_Access_Reject:
1812 if (rq->origusername)
1813 debug(DBG_INFO, "Access Reject for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1815 debug(DBG_INFO, "Access Reject for %s from %s", tmp, server->conf->host);
1820 buf[1] = (char)rq->origid;
1821 memcpy(buf + 4, rq->origauth, 16);
1823 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1826 if (rq->origusername) {
1827 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
1829 pthread_mutex_unlock(&server->newrq_mutex);
1830 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1833 memcpy(username, rq->origusername, strlen(rq->origusername));
1834 len = RADLEN(buf) - 20;
1837 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1841 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
1842 pthread_mutex_unlock(&server->newrq_mutex);
1843 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
1846 debug(DBG_DBG, "replyh: computed messageauthattr");
1849 if (from->conf->type == 'U')
1850 fromsa = rq->fromsa;
1851 /* once we set received = 1, rq may be reused */
1853 pthread_mutex_unlock(&server->newrq_mutex);
1855 debug(DBG_DBG, "replyh: giving packet back to where it came from");
1856 sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
1860 void *udpclientrd(void *arg) {
1861 struct server *server;
1863 int *s = (int *)arg;
1867 buf = radudpget(*s, NULL, &server, NULL);
1868 if (!replyh(server, buf))
1873 void *tlsclientrd(void *arg) {
1874 struct server *server = (struct server *)arg;
1876 struct timeval lastconnecttry;
1879 /* yes, lastconnecttry is really necessary */
1880 lastconnecttry = server->lastconnecttry;
1881 buf = radtlsget(server->ssl);
1883 tlsconnect(server, &lastconnecttry, "clientrd");
1887 if (!replyh(server, buf))
1892 void *clientwr(void *arg) {
1893 struct server *server = (struct server *)arg;
1895 pthread_t tlsclientrdth;
1898 struct timeval now, lastsend;
1899 struct timespec timeout;
1900 struct request statsrvrq;
1901 unsigned char statsrvbuf[38];
1903 memset(&timeout, 0, sizeof(struct timespec));
1905 if (server->conf->statusserver) {
1906 memset(&statsrvrq, 0, sizeof(struct request));
1907 memset(statsrvbuf, 0, sizeof(statsrvbuf));
1908 statsrvbuf[0] = RAD_Status_Server;
1910 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
1911 statsrvbuf[21] = 18;
1912 gettimeofday(&lastsend, NULL);
1915 if (server->conf->type == 'U') {
1916 server->connectionok = 1;
1918 tlsconnect(server, NULL, "new client");
1919 server->connectionok = 1;
1920 if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server))
1921 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
1925 pthread_mutex_lock(&server->newrq_mutex);
1926 if (!server->newrq) {
1927 gettimeofday(&now, NULL);
1928 if (server->conf->statusserver) {
1929 /* random 0-7 seconds */
1930 RAND_bytes(&rnd, 1);
1932 if (!timeout.tv_sec || timeout.tv_sec - now.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
1933 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
1935 if (timeout.tv_sec) {
1936 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1937 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1940 debug(DBG_DBG, "clientwr: waiting for new request");
1941 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1944 if (server->newrq) {
1945 debug(DBG_DBG, "clientwr: got new request");
1948 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1949 pthread_mutex_unlock(&server->newrq_mutex);
1951 for (i = 0; i < MAX_REQUESTS; i++) {
1952 pthread_mutex_lock(&server->newrq_mutex);
1953 while (i < MAX_REQUESTS && !server->requests[i].buf)
1955 if (i == MAX_REQUESTS) {
1956 pthread_mutex_unlock(&server->newrq_mutex);
1959 rq = server->requests + i;
1962 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
1964 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
1966 /* setting this to NULL means that it can be reused */
1969 pthread_mutex_unlock(&server->newrq_mutex);
1973 gettimeofday(&now, NULL);
1974 if (now.tv_sec < rq->expiry.tv_sec) {
1975 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1976 timeout.tv_sec = rq->expiry.tv_sec;
1977 pthread_mutex_unlock(&server->newrq_mutex);
1981 if (rq->tries == (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
1982 ? 1 : REQUEST_RETRIES)) {
1983 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1984 if (*rq->buf == RAD_Status_Server) {
1985 debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->conf->host);
1986 if (server->loststatsrv < 255)
1987 server->loststatsrv++;
1990 /* setting this to NULL means that it can be reused */
1992 pthread_mutex_unlock(&server->newrq_mutex);
1995 pthread_mutex_unlock(&server->newrq_mutex);
1997 rq->expiry.tv_sec = now.tv_sec +
1998 (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
1999 ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
2000 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2001 timeout.tv_sec = rq->expiry.tv_sec;
2003 clientradput(server, server->requests[i].buf);
2004 gettimeofday(&lastsend, NULL);
2006 if (server->conf->statusserver) {
2007 gettimeofday(&now, NULL);
2008 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
2009 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2010 debug(DBG_WARN, "clientwr: failed to generate random auth");
2013 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2014 if (!statsrvrq.buf) {
2015 debug(DBG_ERR, "clientwr: malloc failed");
2018 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2019 debug(DBG_DBG, "clientwr: sending status server to %s", server->conf->host);
2020 lastsend.tv_sec = now.tv_sec;
2021 sendrq(server, &statsrvrq);
2027 void *udpserverwr(void *arg) {
2028 struct replyq *replyq = udp_server_replyq;
2029 struct reply *reply;
2032 pthread_mutex_lock(&replyq->mutex);
2033 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2034 debug(DBG_DBG, "udp server writer, waiting for signal");
2035 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2036 debug(DBG_DBG, "udp server writer, got signal");
2038 pthread_mutex_unlock(&replyq->mutex);
2040 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
2041 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2042 debug(DBG_WARN, "sendudp: send failed");
2048 void *udpserverrd(void *arg) {
2050 pthread_t udpserverwrth;
2051 struct clsrvconf *listenres;
2053 listenres = resolve_hostport('U', options.listenudp, DEFAULT_UDP_PORT);
2054 if ((udp_server_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2055 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2057 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
2058 listenres->host ? listenres->host : "*", listenres->port);
2061 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
2062 debugx(1, DBG_ERR, "pthread_create failed");
2065 memset(&rq, 0, sizeof(struct request));
2066 rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
2071 void *udpaccserverrd(void *arg) {
2073 struct clsrvconf *listenres;
2075 listenres = resolve_hostport('U', options.listenaccudp, DEFAULT_UDP_PORT);
2076 if ((udp_accserver_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2077 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2079 debug(DBG_WARN, "udpaccserverrd: listening for UDP on %s:%s",
2080 listenres->host ? listenres->host : "*", listenres->port);
2084 memset(&rq, 0, sizeof(struct request));
2085 rq.buf = radudpget(udp_accserver_sock, &rq.from, NULL, &rq.fromsa);
2086 if (*(uint8_t *)rq.buf == RAD_Accounting_Request) {
2090 debug(DBG_INFO, "udpaccserverrd: got something other than accounting-request, ignoring");
2095 void *tlsserverwr(void *arg) {
2097 unsigned long error;
2098 struct client *client = (struct client *)arg;
2099 struct replyq *replyq;
2100 struct reply *reply;
2102 debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
2103 replyq = client->replyq;
2105 pthread_mutex_lock(&replyq->mutex);
2106 while (!list_first(replyq->replies)) {
2108 debug(DBG_DBG, "tls server writer, waiting for signal");
2109 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2110 debug(DBG_DBG, "tls server writer, got signal");
2113 /* ssl might have changed while waiting */
2114 pthread_mutex_unlock(&replyq->mutex);
2115 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2119 reply = (struct reply *)list_shift(replyq->replies);
2120 pthread_mutex_unlock(&replyq->mutex);
2121 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2123 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
2124 cnt, RADLEN(reply->buf));
2126 while ((error = ERR_get_error()))
2127 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2133 void *tlsserverrd(void *arg) {
2135 unsigned long error;
2137 struct client *client = (struct client *)arg;
2138 pthread_t tlsserverwrth;
2141 debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2144 if (SSL_accept(ssl) <= 0) {
2145 while ((error = ERR_get_error()))
2146 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2147 debug(DBG_ERR, "SSL_accept failed");
2150 if (tlsverifycert(client->ssl, client->conf)) {
2151 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2152 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2156 memset(&rq, 0, sizeof(struct request));
2157 rq.buf = radtlsget(client->ssl);
2160 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2164 debug(DBG_ERR, "tlsserverrd: connection lost");
2165 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2167 pthread_mutex_lock(&client->replyq->mutex);
2168 pthread_cond_signal(&client->replyq->cond);
2169 pthread_mutex_unlock(&client->replyq->mutex);
2170 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2171 pthread_join(tlsserverwrth, NULL);
2175 s = SSL_get_fd(ssl);
2177 shutdown(s, SHUT_RDWR);
2179 debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->conf->host);
2180 removeclient(client);
2185 pthread_t tlsserverth;
2187 struct sockaddr_storage from;
2188 size_t fromlen = sizeof(from);
2189 struct clsrvconf *conf;
2190 struct client *client;
2191 struct clsrvconf *listenres;
2193 listenres = resolve_hostport('T', options.listentcp, DEFAULT_TLS_PORT);
2194 if ((s = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2195 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
2198 debug(DBG_WARN, "listening for incoming TCP on %s:%s", listenres->host ? listenres->host : "*", listenres->port);
2202 snew = accept(s, (struct sockaddr *)&from, &fromlen);
2204 debug(DBG_WARN, "accept failed");
2207 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2209 conf = find_conf('T', (struct sockaddr *)&from, clconfs, NULL);
2211 debug(DBG_WARN, "ignoring request, not a known TLS client");
2212 shutdown(snew, SHUT_RDWR);
2217 client = addclient(conf);
2220 debug(DBG_WARN, "Failed to create new client instance");
2221 shutdown(snew, SHUT_RDWR);
2225 client->ssl = SSL_new(client->conf->ssl_ctx);
2226 SSL_set_fd(client->ssl, snew);
2227 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
2228 debug(DBG_ERR, "tlslistener: pthread_create failed");
2229 SSL_free(client->ssl);
2230 removeclient(client);
2231 shutdown(snew, SHUT_RDWR);
2235 pthread_detach(tlsserverth);
2240 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
2243 STACK_OF(X509_NAME) *calist;
2245 unsigned long error;
2247 if (!certfile || !certkeyfile)
2248 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2250 if (!cacertfile && !cacertpath)
2251 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2254 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2255 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2256 for (i = 0; i < CRYPTO_num_locks(); i++) {
2257 ssl_lock_count[i] = 0;
2258 pthread_mutex_init(&ssl_locks[i], NULL);
2260 CRYPTO_set_id_callback(ssl_thread_id);
2261 CRYPTO_set_locking_callback(ssl_locking_callback);
2263 SSL_load_error_strings();
2266 while (!RAND_status()) {
2267 time_t t = time(NULL);
2268 pid_t pid = getpid();
2269 RAND_seed((unsigned char *)&t, sizeof(time_t));
2270 RAND_seed((unsigned char *)&pid, sizeof(pid));
2273 ctx = SSL_CTX_new(TLSv1_method());
2275 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2276 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2278 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2279 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2280 !SSL_CTX_check_private_key(ctx) ||
2281 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2282 while ((error = ERR_get_error()))
2283 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2284 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2287 calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
2288 if (!cacertfile || calist) {
2291 calist = sk_X509_NAME_new_null();
2292 if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
2293 sk_X509_NAME_free(calist);
2299 while ((error = ERR_get_error()))
2300 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2301 debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
2303 SSL_CTX_set_client_CA_list(ctx, calist);
2305 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2306 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2308 new = malloc(sizeof(struct tls));
2309 if (!new || !list_push(tlsconfs, new))
2310 debugx(1, DBG_ERR, "malloc failed");
2312 memset(new, 0, sizeof(struct tls));
2313 new->name = stringcopy(value, 0);
2315 debugx(1, DBG_ERR, "malloc failed");
2318 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2322 struct list_node *entry;
2325 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2326 t = (struct tls *)entry->data;
2330 SSL_CTX_free(t->ctx);
2332 list_destroy(tlsconfs);
2336 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2337 struct list_node *entry;
2338 struct tls *t, *t1 = NULL, *t2 = NULL;
2340 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2341 t = (struct tls *)entry->data;
2342 if (!strcasecmp(t->name, alt1)) {
2346 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2357 void addrealm(char *value, char **servers, char *message) {
2359 struct realm *realm;
2360 char *s, *regex = NULL;
2361 struct list_node *entry;
2362 struct clsrvconf *conf;
2364 if (*value == '/') {
2365 /* regexp, remove optional trailing / if present */
2366 if (value[strlen(value) - 1] == '/')
2367 value[strlen(value) - 1] = '\0';
2369 /* not a regexp, let us make it one */
2370 if (*value == '*' && !value[1])
2371 regex = stringcopy(".*", 0);
2373 for (n = 0, s = value; *s;)
2376 regex = malloc(strlen(value) + n + 3);
2379 for (n = 1, s = value; *s; s++) {
2389 debugx(1, DBG_ERR, "malloc failed");
2390 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2393 realm = malloc(sizeof(struct realm));
2395 debugx(1, DBG_ERR, "malloc failed");
2397 memset(realm, 0, sizeof(struct realm));
2398 realm->name = stringcopy(value, 0);
2400 debugx(1, DBG_ERR, "malloc failed");
2401 if (message && strlen(message) > 253)
2402 debugx(1, DBG_ERR, "ReplyMessage can be at most 253 bytes");
2403 realm->message = message;
2405 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB))
2406 debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2410 if (servers && *servers) {
2411 realm->srvconfs = list_create();
2412 if (!realm->srvconfs)
2413 debugx(1, DBG_ERR, "malloc failed");
2414 for (n = 0; servers[n]; n++) {
2415 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2416 conf = (struct clsrvconf *)entry->data;
2417 if (!strcasecmp(servers[n], conf->name))
2421 debugx(1, DBG_ERR, "addrealm failed, no server %s", servers[n]);
2422 if (!list_push(realm->srvconfs, conf))
2423 debugx(1, DBG_ERR, "malloc failed");
2424 debug(DBG_DBG, "addrealm: added server %s for realm %s", conf->name, value);
2427 realm->srvconfs = NULL;
2429 if (!list_push(realms, realm))
2430 debugx(1, DBG_ERR, "malloc failed");
2431 debug(DBG_DBG, "addrealm: added realm %s", value);
2434 struct gconffile *openconfigfile(const char *filename) {
2436 char pathname[100], *base = NULL;
2437 struct gconffile *cf = NULL;
2439 f = pushgconffile(&cf, filename);
2441 debug(DBG_DBG, "reading config file %s", filename);
2445 if (strlen(filename) + 1 <= sizeof(pathname)) {
2446 /* basename() might modify the string */
2447 strcpy(pathname, filename);
2448 base = basename(pathname);
2449 f = pushgconffile(&cf, base);
2453 debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
2455 debug(DBG_DBG, "reading config file %s", base);
2459 int addmatchcertattr(struct clsrvconf *conf, char *matchcertattr) {
2462 v = matchcertattr + 20;
2463 if (strncasecmp(matchcertattr, "SubjectAltName:URI:/", 20) || !*v)
2465 /* regexp, remove optional trailing / if present */
2466 if (v[strlen(v) - 1] == '/')
2467 v[strlen(v) - 1] = '\0';
2471 conf->certuriregex = malloc(sizeof(regex_t));
2472 if (!conf->certuriregex) {
2473 debug(DBG_ERR, "malloc failed");
2476 if (regcomp(conf->certuriregex, v, REG_ICASE | REG_NOSUB)) {
2477 free(conf->certuriregex);
2478 conf->certuriregex = NULL;
2479 debug(DBG_ERR, "failed to compile regular expression %s", v);
2485 int addrewriteattr(struct clsrvconf *conf, char *rewriteattr) {
2488 v = rewriteattr + 11;
2489 if (strncasecmp(rewriteattr, "User-Name:/", 11) || !*v)
2491 /* regexp, remove optional trailing / if present */
2492 if (v[strlen(v) - 1] == '/')
2493 v[strlen(v) - 1] = '\0';
2501 conf->rewriteattrregex = malloc(sizeof(regex_t));
2502 if (!conf->rewriteattrregex) {
2503 debug(DBG_ERR, "malloc failed");
2507 conf->rewriteattrreplacement = stringcopy(w, 0);
2508 if (!conf->rewriteattrreplacement) {
2509 free(conf->rewriteattrregex);
2510 conf->rewriteattrregex = NULL;
2514 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
2515 free(conf->rewriteattrregex);
2516 conf->rewriteattrregex = NULL;
2517 free(conf->rewriteattrreplacement);
2518 conf->rewriteattrreplacement = NULL;
2519 debug(DBG_ERR, "failed to compile regular expression %s", v);
2526 void confclient_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2527 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *rewriteattr = NULL;
2528 struct clsrvconf *conf;
2530 debug(DBG_DBG, "confclient_cb called for %s", block);
2532 conf = malloc(sizeof(struct clsrvconf));
2533 if (!conf || !list_push(clconfs, conf))
2534 debugx(1, DBG_ERR, "malloc failed");
2535 memset(conf, 0, sizeof(struct clsrvconf));
2537 getgenericconfig(cf, block,
2538 "type", CONF_STR, &type,
2539 "host", CONF_STR, &conf->host,
2540 "secret", CONF_STR, &conf->secret,
2541 "tls", CONF_STR, &tls,
2542 "matchcertificateattribute", CONF_STR, &matchcertattr,
2543 "rewriteattribute", CONF_STR, &rewriteattr,
2547 /* leave conf->name to be NULL for clients */
2549 conf->host = stringcopy(val, 0);
2551 if (type && !strcasecmp(type, "udp")) {
2554 } else if (type && !strcasecmp(type, "tls")) {
2555 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultclient", "default");
2557 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2558 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2559 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2563 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2568 free(matchcertattr);
2571 if (!addrewriteattr(conf, rewriteattr))
2572 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2576 if (!resolvepeer(conf, 0))
2577 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2579 if (!conf->secret) {
2580 if (conf->type == 'U')
2581 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2582 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2586 void confserver_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2587 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *statusserver = NULL;
2588 struct clsrvconf *conf;
2590 debug(DBG_DBG, "confserver_cb called for %s", block);
2592 conf = malloc(sizeof(struct clsrvconf));
2593 if (!conf || !list_push(srvconfs, conf))
2594 debugx(1, DBG_ERR, "malloc failed");
2595 memset(conf, 0, sizeof(struct clsrvconf));
2597 getgenericconfig(cf, block,
2598 "type", CONF_STR, &type,
2599 "host", CONF_STR, &conf->host,
2600 "port", CONF_STR, &conf->port,
2601 "secret", CONF_STR, &conf->secret,
2602 "tls", CONF_STR, &tls,
2603 "matchcertificateattribute", CONF_STR, &matchcertattr,
2604 "StatusServer", CONF_STR, &statusserver,
2608 conf->name = stringcopy(val, 0);
2610 conf->host = stringcopy(val, 0);
2612 if (type && !strcasecmp(type, "udp")) {
2616 conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
2617 } else if (type && !strcasecmp(type, "tls")) {
2618 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultserver", "default");
2620 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2621 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2622 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2624 conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
2628 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2633 free(matchcertattr);
2635 if (!resolvepeer(conf, 0))
2636 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2638 if (!conf->secret) {
2639 if (conf->type == 'U')
2640 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2641 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2645 if (!strcasecmp(statusserver, "on"))
2646 conf->statusserver = 1;
2647 else if (strcasecmp(statusserver, "off"))
2648 debugx(1, DBG_ERR, "error in block %s, StatusServer is %s, must be on or off", block, statusserver);
2653 void confrealm_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2654 char **servers = NULL, *msg = NULL;
2656 debug(DBG_DBG, "confrealm_cb called for %s", block);
2658 getgenericconfig(cf, block,
2659 "server", CONF_MSTR, &servers,
2660 "ReplyMessage", CONF_STR, &msg,
2664 addrealm(val, servers, msg);
2668 void conftls_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2669 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
2671 debug(DBG_DBG, "conftls_cb called for %s", block);
2673 getgenericconfig(cf, block,
2674 "CACertificateFile", CONF_STR, &cacertfile,
2675 "CACertificatePath", CONF_STR, &cacertpath,
2676 "CertificateFile", CONF_STR, &certfile,
2677 "CertificateKeyFile", CONF_STR, &certkeyfile,
2678 "CertificateKeyPassword", CONF_STR, &certkeypwd,
2682 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
2690 void getmainconfig(const char *configfile) {
2691 char *loglevel = NULL;
2692 struct gconffile *cfs;
2694 cfs = openconfigfile(configfile);
2695 memset(&options, 0, sizeof(options));
2697 clconfs = list_create();
2699 debugx(1, DBG_ERR, "malloc failed");
2701 srvconfs = list_create();
2703 debugx(1, DBG_ERR, "malloc failed");
2705 realms = list_create();
2707 debugx(1, DBG_ERR, "malloc failed");
2709 tlsconfs = list_create();
2711 debugx(1, DBG_ERR, "malloc failed");
2713 getgenericconfig(&cfs, NULL,
2714 "ListenUDP", CONF_STR, &options.listenudp,
2715 "ListenTCP", CONF_STR, &options.listentcp,
2716 "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
2717 "SourceUDP", CONF_STR, &options.sourceudp,
2718 "SourceTCP", CONF_STR, &options.sourcetcp,
2719 "LogLevel", CONF_STR, &loglevel,
2720 "LogDestination", CONF_STR, &options.logdestination,
2721 "Client", CONF_CBK, confclient_cb,
2722 "Server", CONF_CBK, confserver_cb,
2723 "Realm", CONF_CBK, confrealm_cb,
2724 "TLS", CONF_CBK, conftls_cb,
2731 if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
2732 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
2733 options.loglevel = *loglevel - '0';
2738 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
2741 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
2744 *configfile = optarg;
2747 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
2748 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
2749 *loglevel = *optarg - '0';
2758 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
2763 if (!(argc - optind))
2767 debug(DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
2771 int main(int argc, char **argv) {
2772 pthread_t udpserverth, udpaccserverth, udpclient4rdth, udpclient6rdth;
2773 struct list_node *entry;
2774 uint8_t foreground = 0, pretend = 0, loglevel = 0;
2775 char *configfile = NULL;
2777 debug_init("radsecproxy");
2778 debug_set_level(DEBUG_LEVEL);
2779 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
2781 debug_set_level(loglevel);
2782 getmainconfig(configfile ? configfile : CONFIG_MAIN);
2784 options.loglevel = loglevel;
2785 else if (options.loglevel)
2786 debug_set_level(options.loglevel);
2788 options.logdestination = NULL;
2790 if (!options.logdestination)
2791 options.logdestination = "x-syslog:///";
2792 debug_set_destination(options.logdestination);
2796 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
2798 if (!list_first(clconfs))
2799 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
2800 if (!list_first(srvconfs))
2801 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
2802 if (!list_first(realms))
2803 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
2805 if (!foreground && (daemon(0, 0) < 0))
2806 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
2808 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
2810 if (client_udp_count) {
2811 udp_server_replyq = newreplyq();
2812 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
2813 debugx(1, DBG_ERR, "pthread_create failed");
2814 if (options.listenaccudp)
2815 if (pthread_create(&udpaccserverth, NULL, udpaccserverrd, NULL))
2816 debugx(1, DBG_ERR, "pthread_create failed");
2819 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2820 addserver((struct clsrvconf *)entry->data);
2821 if (pthread_create(&((struct clsrvconf *)entry->data)->servers->clientth, NULL, clientwr,
2822 (void *)((struct clsrvconf *)entry->data)->servers))
2823 debugx(1, DBG_ERR, "pthread_create failed");
2825 /* srcudpres no longer needed, while srctcpres is needed later */
2830 if (udp_client4_sock >= 0)
2831 if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
2832 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
2833 if (udp_client6_sock >= 0)
2834 if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
2835 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
2837 if (client_tls_count)
2838 return tlslistener();
2840 /* just hang around doing nothing, anything to do here? */