2 * Copyright (C) 2006-2008 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 /* Code contributions from:
11 * Arne Schwabe <schwabe at uni-paderborn.de>
14 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
15 * rd is responsible for init and launching wr
16 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
17 * each tlsserverrd launches tlsserverwr
18 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
19 * for init and launching rd
21 * serverrd will receive a request, processes it and puts it in the requestq of
22 * the appropriate clientwr
23 * clientwr monitors its requestq and sends requests
24 * clientrd looks for responses, processes them and puts them in the replyq of
25 * the peer the request came from
26 * serverwr monitors its reply and sends replies
28 * In addition to the main thread, we have:
29 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
30 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
31 * For each TLS peer connecting to us there will be 2 more TLS threads
32 * This is only for connected peers
33 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
34 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
38 #include <sys/socket.h>
39 #include <netinet/in.h>
48 #include <sys/types.h>
49 #include <arpa/inet.h>
53 #include <openssl/ssl.h>
54 #include <openssl/rand.h>
55 #include <openssl/err.h>
56 #include <openssl/md5.h>
57 #include <openssl/hmac.h>
58 #include <openssl/x509v3.h>
63 #include "radsecproxy.h"
65 static struct options options;
66 struct list *clconfs, *srvconfs, *realms, *tlsconfs, *rewriteconfs;
68 static int client_udp_count = 0;
69 static int client_tls_count = 0;
71 static struct addrinfo *srcudpres = NULL;
72 static struct addrinfo *srctcpres = NULL;
74 static struct replyq *udp_server_replyq = NULL;
75 static int udp_server_sock = -1;
76 static int udp_accserver_sock = -1;
77 static int udp_client4_sock = -1;
78 static int udp_client6_sock = -1;
79 static pthread_mutex_t *ssl_locks = NULL;
80 static long *ssl_lock_count;
84 /* callbacks for making OpenSSL thread safe */
85 unsigned long ssl_thread_id() {
86 return (unsigned long)pthread_self();
89 void ssl_locking_callback(int mode, int type, const char *file, int line) {
90 if (mode & CRYPTO_LOCK) {
91 pthread_mutex_lock(&ssl_locks[type]);
92 ssl_lock_count[type]++;
94 pthread_mutex_unlock(&ssl_locks[type]);
97 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
98 int pwdlen = strlen(userdata);
99 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
101 memcpy(buf, userdata, pwdlen);
105 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
110 err_cert = X509_STORE_CTX_get_current_cert(ctx);
111 err = X509_STORE_CTX_get_error(ctx);
112 depth = X509_STORE_CTX_get_error_depth(ctx);
114 if (depth > MAX_CERT_DEPTH) {
116 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
117 X509_STORE_CTX_set_error(ctx, err);
121 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
122 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
125 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
126 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
127 debug(DBG_WARN, "\tIssuer=%s", buf);
129 case X509_V_ERR_CERT_NOT_YET_VALID:
130 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
131 debug(DBG_WARN, "\tCertificate not yet valid");
133 case X509_V_ERR_CERT_HAS_EXPIRED:
134 debug(DBG_WARN, "Certificate has expired");
136 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
137 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
142 printf("certificate verify returns %d\n", ok);
147 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
148 struct addrinfo hints, *addrinfo, *res;
152 slash = conf->host ? strchr(conf->host, '/') : NULL;
156 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
160 if (*s < '0' || *s > '9') {
161 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
164 plen = atoi(slash + 1);
165 if (plen < 0 || plen > 128) {
166 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
171 memset(&hints, 0, sizeof(hints));
172 hints.ai_socktype = (conf->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
173 hints.ai_family = AF_UNSPEC;
174 hints.ai_flags = ai_flags;
175 if (!conf->host && !conf->port) {
176 /* getaddrinfo() doesn't like host and port to be NULL */
177 if (getaddrinfo(conf->host, DEFAULT_UDP_PORT, &hints, &addrinfo)) {
178 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
181 for (res = addrinfo; res; res = res->ai_next)
182 port_set(res->ai_addr, 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->host : "(null)", conf->port ? conf->port : "(null)");
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->host : "(null)", conf->port ? conf->port : "(null)");
303 void freeclsrvres(struct clsrvconf *res) {
307 freeaddrinfo(res->addrinfo);
311 int connecttcp(struct addrinfo *addrinfo) {
313 struct addrinfo *res;
316 for (res = addrinfo; res; res = res->ai_next) {
317 s = bindtoaddr(srctcpres, res->ai_family, 1, 1);
319 debug(DBG_WARN, "connecttoserver: socket failed");
322 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
324 debug(DBG_WARN, "connecttoserver: connect failed");
331 /* returns 1 if the len first bits are equal, else 0 */
332 int prefixmatch(void *a1, void *a2, uint8_t len) {
333 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
335 if (l && memcmp(a1, a2, l))
340 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
343 /* returns next config with matching address, or NULL */
344 struct clsrvconf *find_conf(char type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
345 struct sockaddr_in6 *sa6 = NULL;
346 struct in_addr *a4 = NULL;
347 struct addrinfo *res;
348 struct list_node *entry;
349 struct clsrvconf *conf;
351 if (addr->sa_family == AF_INET6) {
352 sa6 = (struct sockaddr_in6 *)addr;
353 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
354 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
358 a4 = &((struct sockaddr_in *)addr)->sin_addr;
360 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
361 conf = (struct clsrvconf *)entry->data;
362 if (conf->type == type) {
363 if (conf->prefixlen == 255) {
364 for (res = conf->addrinfo; res; res = res->ai_next)
365 if ((a4 && res->ai_family == AF_INET &&
366 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
367 (sa6 && res->ai_family == AF_INET6 &&
368 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
374 res = conf->addrinfo;
376 ((a4 && res->ai_family == AF_INET &&
377 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
378 (sa6 && res->ai_family == AF_INET6 &&
379 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
390 struct replyq *newreplyq() {
391 struct replyq *replyq;
393 replyq = malloc(sizeof(struct replyq));
395 debugx(1, DBG_ERR, "malloc failed");
396 replyq->replies = list_create();
397 if (!replyq->replies)
398 debugx(1, DBG_ERR, "malloc failed");
399 pthread_mutex_init(&replyq->mutex, NULL);
400 pthread_cond_init(&replyq->cond, NULL);
404 struct client *addclient(struct clsrvconf *conf) {
405 struct client *new = malloc(sizeof(struct client));
408 debug(DBG_ERR, "malloc failed");
411 if (!conf->clients) {
412 conf->clients = list_create();
413 if (!conf->clients) {
414 debug(DBG_ERR, "malloc failed");
419 memset(new, 0, sizeof(struct client));
421 new->replyq = conf->type == 'T' ? newreplyq() : udp_server_replyq;
423 list_push(conf->clients, new);
427 void removeclient(struct client *client) {
428 struct list_node *entry;
430 if (!client || !client->conf->clients)
433 pthread_mutex_lock(&client->replyq->mutex);
434 for (entry = list_first(client->replyq->replies); entry; entry = list_next(entry))
435 free(((struct reply *)entry)->buf);
436 list_destroy(client->replyq->replies);
437 pthread_cond_destroy(&client->replyq->cond);
438 pthread_mutex_unlock(&client->replyq->mutex);
439 pthread_mutex_destroy(&client->replyq->mutex);
440 list_removedata(client->conf->clients, client);
445 void removeclientrqs(struct client *client) {
446 struct list_node *entry;
447 struct server *server;
451 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
452 server = ((struct clsrvconf *)entry->data)->servers;
453 pthread_mutex_lock(&server->newrq_mutex);
454 for (i = 0; i < MAX_REQUESTS; i++) {
455 rq = server->requests + i;
456 if (rq->from == client)
459 pthread_mutex_unlock(&server->newrq_mutex);
463 void addserver(struct clsrvconf *conf) {
464 struct clsrvconf *res;
467 debugx(1, DBG_ERR, "addserver: currently works with just one server per conf");
469 conf->servers = malloc(sizeof(struct server));
471 debugx(1, DBG_ERR, "malloc failed");
472 memset(conf->servers, 0, sizeof(struct server));
473 conf->servers->conf = conf;
475 if (conf->type == 'U') {
477 res = resolve_hostport('U', options.sourceudp, NULL);
478 srcudpres = res->addrinfo;
479 res->addrinfo = NULL;
482 switch (conf->addrinfo->ai_family) {
484 if (udp_client4_sock < 0) {
485 udp_client4_sock = bindtoaddr(srcudpres, AF_INET, 0, 1);
486 if (udp_client4_sock < 0)
487 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
489 conf->servers->sock = udp_client4_sock;
492 if (udp_client6_sock < 0) {
493 udp_client6_sock = bindtoaddr(srcudpres, AF_INET6, 0, 1);
494 if (udp_client6_sock < 0)
495 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
497 conf->servers->sock = udp_client6_sock;
500 debugx(1, DBG_ERR, "addserver: unsupported address family");
505 res = resolve_hostport('T', options.sourcetcp, NULL);
506 srctcpres = res->addrinfo;
507 res->addrinfo = NULL;
510 conf->servers->sock = -1;
513 pthread_mutex_init(&conf->servers->lock, NULL);
514 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
515 if (!conf->servers->requests)
516 debugx(1, DBG_ERR, "malloc failed");
517 conf->servers->newrq = 0;
518 pthread_mutex_init(&conf->servers->newrq_mutex, NULL);
519 pthread_cond_init(&conf->servers->newrq_cond, NULL);
522 /* exactly one of client and server must be non-NULL */
523 /* return who we received from in *client or *server */
524 /* return from in sa if not NULL */
525 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
527 unsigned char buf[4], *rad;
528 struct sockaddr_storage from;
529 socklen_t fromlen = sizeof(from);
531 struct list_node *node;
537 if (select(s + 1, &readfds, NULL, NULL, NULL) < 1)
539 cnt = recvfrom(s, buf, 4, MSG_PEEK, (struct sockaddr *)&from, &fromlen);
541 debug(DBG_WARN, "radudpget: recv failed");
545 p = find_conf('U', (struct sockaddr *)&from, client ? clconfs : srvconfs, NULL);
547 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer %s, ignoring", addr2string((struct sockaddr *)&from));
554 debug(DBG_WARN, "radudpget: length too small");
561 debug(DBG_ERR, "radudpget: malloc failed");
566 cnt = recv(s, rad, len, MSG_TRUNC);
567 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from));
570 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
576 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
579 node = list_first(p->clients);
580 *client = node ? (struct client *)node->data : addclient(p);
586 *server = p->servers;
594 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
595 int loc, i, l, n, r = 0;
598 STACK_OF(GENERAL_NAME) *alt;
601 debug(DBG_DBG, "subjectaltnameaddr");
603 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
607 ex = X509_get_ext(cert, loc);
608 alt = X509V3_EXT_d2i(ex);
612 n = sk_GENERAL_NAME_num(alt);
613 for (i = 0; i < n; i++) {
614 gn = sk_GENERAL_NAME_value(alt, i);
615 if (gn->type != GEN_IPADD)
618 v = (char *)ASN1_STRING_data(gn->d.ia5);
619 l = ASN1_STRING_length(gn->d.ia5);
620 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
621 && !memcmp(v, &addr, l)) {
626 GENERAL_NAMES_free(alt);
630 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
637 nm = X509_get_subject_name(cert);
640 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
643 e = X509_NAME_get_entry(nm, loc);
644 t = X509_NAME_ENTRY_get_data(e);
645 v = (char *) ASN1_STRING_data(t);
646 l = ASN1_STRING_length(t);
650 if (l == strlen(exact) && !strncasecmp(exact, v, l))
653 s = stringcopy((char *)v, l);
655 debug(DBG_ERR, "malloc failed");
658 if (regexec(regex, s, 0, NULL, 0)) {
669 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
670 int loc, i, l, n, r = 0;
673 STACK_OF(GENERAL_NAME) *alt;
676 debug(DBG_DBG, "subjectaltnameregexp");
678 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
682 ex = X509_get_ext(cert, loc);
683 alt = X509V3_EXT_d2i(ex);
687 n = sk_GENERAL_NAME_num(alt);
688 for (i = 0; i < n; i++) {
689 gn = sk_GENERAL_NAME_value(alt, i);
690 if (gn->type != type)
693 v = (char *)ASN1_STRING_data(gn->d.ia5);
694 l = ASN1_STRING_length(gn->d.ia5);
698 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
701 if (memcmp(v, exact, l))
704 s = stringcopy((char *)v, l);
706 debug(DBG_ERR, "malloc failed");
709 if (regexec(regex, s, 0, NULL, 0)) {
718 GENERAL_NAMES_free(alt);
722 X509 *verifytlscert(SSL *ssl) {
726 if (SSL_get_verify_result(ssl) != X509_V_OK) {
727 debug(DBG_ERR, "verifytlscert: basic validation failed");
728 while ((error = ERR_get_error()))
729 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
733 cert = SSL_get_peer_certificate(ssl);
735 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
739 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
741 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
742 struct in6_addr addr;
744 if (conf->certnamecheck && conf->prefixlen == 255) {
745 if (inet_pton(AF_INET, conf->host, &addr))
747 else if (inet_pton(AF_INET6, conf->host, &addr))
750 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
753 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
756 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
758 if (!cnregexp(cert, conf->host, NULL)) {
759 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
762 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
765 if (conf->certcnregex) {
766 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
767 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
770 debug(DBG_DBG, "verifyconfcert: CN matching regex");
772 if (conf->certuriregex) {
773 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
774 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
777 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
782 void tlsconnect(struct server *server, struct timeval *when, char *text) {
787 debug(DBG_DBG, "tlsconnect called from %s", text);
788 pthread_mutex_lock(&server->lock);
789 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
790 /* already reconnected, nothing to do */
791 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
792 pthread_mutex_unlock(&server->lock);
796 debug(DBG_DBG, "tlsconnect %s", text);
799 gettimeofday(&now, NULL);
800 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
801 if (server->connectionok) {
802 server->connectionok = 0;
804 } else if (elapsed < 1)
806 else if (elapsed < 60) {
807 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
809 } else if (elapsed < 100000) {
810 debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
813 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
814 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
815 if (server->sock >= 0)
817 if ((server->sock = connecttcp(server->conf->addrinfo)) < 0) {
818 debug(DBG_ERR, "tlsconnect: connecttcp failed");
822 SSL_free(server->ssl);
823 server->ssl = SSL_new(server->conf->ssl_ctx);
824 SSL_set_fd(server->ssl, server->sock);
825 if (SSL_connect(server->ssl) <= 0)
827 cert = verifytlscert(server->ssl);
830 if (verifyconfcert(cert, server->conf)) {
836 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
837 gettimeofday(&server->lastconnecttry, NULL);
838 pthread_mutex_unlock(&server->lock);
841 unsigned char *radtlsget(SSL *ssl) {
843 unsigned char buf[4], *rad;
846 for (total = 0; total < 4; total += cnt) {
847 cnt = SSL_read(ssl, buf + total, 4 - total);
849 debug(DBG_ERR, "radtlsget: connection lost");
850 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
851 /* remote end sent close_notify, send one back */
861 debug(DBG_ERR, "radtlsget: malloc failed");
866 for (; total < len; total += cnt) {
867 cnt = SSL_read(ssl, rad + total, len - total);
869 debug(DBG_ERR, "radtlsget: connection lost");
870 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
871 /* remote end sent close_notify, send one back */
883 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
886 debug(DBG_DBG, "radtlsget: got %d bytes", total);
890 int clientradputudp(struct server *server, unsigned char *rad) {
892 struct sockaddr_storage sa;
893 struct sockaddr *sap;
894 struct clsrvconf *conf = server->conf;
898 port = port_get(conf->addrinfo->ai_addr);
900 if (*rad == RAD_Accounting_Request) {
901 sap = (struct sockaddr *)&sa;
902 memcpy(sap, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen);
903 port_set(sap, ++port);
905 sap = conf->addrinfo->ai_addr;
907 if (sendto(server->sock, rad, len, 0, sap, conf->addrinfo->ai_addrlen) >= 0) {
908 debug(DBG_DBG, "clienradputudp: sent UDP of length %d to %s port %d", len, conf->host, port);
912 debug(DBG_WARN, "clientradputudp: send failed");
916 int clientradputtls(struct server *server, unsigned char *rad) {
920 struct timeval lastconnecttry;
921 struct clsrvconf *conf = server->conf;
924 lastconnecttry = server->lastconnecttry;
925 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
926 while ((error = ERR_get_error()))
927 debug(DBG_ERR, "clientradputtls: TLS: %s", ERR_error_string(error, NULL));
928 tlsconnect(server, &lastconnecttry, "clientradputtls");
929 lastconnecttry = server->lastconnecttry;
932 server->connectionok = 1;
933 debug(DBG_DBG, "clientradputtls: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
937 int clientradput(struct server *server, unsigned char *rad) {
938 switch (server->conf->type) {
940 return clientradputudp(server, rad);
942 return clientradputtls(server, rad);
947 int radsign(unsigned char *rad, unsigned char *sec) {
948 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
949 static unsigned char first = 1;
950 static EVP_MD_CTX mdctx;
954 pthread_mutex_lock(&lock);
956 EVP_MD_CTX_init(&mdctx);
960 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
961 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
962 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
963 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
965 pthread_mutex_unlock(&lock);
969 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
970 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
971 static unsigned char first = 1;
972 static EVP_MD_CTX mdctx;
973 unsigned char hash[EVP_MAX_MD_SIZE];
977 pthread_mutex_lock(&lock);
979 EVP_MD_CTX_init(&mdctx);
985 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
986 EVP_DigestUpdate(&mdctx, rad, 4) &&
987 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
988 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
989 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
990 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
992 !memcmp(hash, rad + 4, 16));
993 pthread_mutex_unlock(&lock);
997 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
998 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
999 static unsigned char first = 1;
1000 static HMAC_CTX hmacctx;
1001 unsigned int md_len;
1002 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
1004 pthread_mutex_lock(&lock);
1006 HMAC_CTX_init(&hmacctx);
1010 memcpy(auth, authattr, 16);
1011 memset(authattr, 0, 16);
1013 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1014 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1015 HMAC_Final(&hmacctx, hash, &md_len);
1016 memcpy(authattr, auth, 16);
1018 debug(DBG_WARN, "message auth computation failed");
1019 pthread_mutex_unlock(&lock);
1023 if (memcmp(auth, hash, 16)) {
1024 debug(DBG_WARN, "message authenticator, wrong value");
1025 pthread_mutex_unlock(&lock);
1029 pthread_mutex_unlock(&lock);
1033 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
1034 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1035 static unsigned char first = 1;
1036 static HMAC_CTX hmacctx;
1037 unsigned int md_len;
1042 pthread_mutex_lock(&lock);
1044 HMAC_CTX_init(&hmacctx);
1048 memset(authattrval, 0, 16);
1050 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1051 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1052 HMAC_Final(&hmacctx, authattrval, &md_len);
1054 debug(DBG_WARN, "message auth computation failed");
1055 pthread_mutex_unlock(&lock);
1059 pthread_mutex_unlock(&lock);
1063 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
1064 while (length > 1) {
1065 if (ATTRTYPE(attrs) == type)
1067 length -= ATTRLEN(attrs);
1068 attrs += ATTRLEN(attrs);
1073 void freerqdata(struct request *rq) {
1074 if (rq->origusername)
1075 free(rq->origusername);
1080 void sendrq(struct server *to, struct request *rq) {
1084 pthread_mutex_lock(&to->newrq_mutex);
1085 /* might simplify if only try nextid, might be ok */
1086 for (i = to->nextid; i < MAX_REQUESTS; i++)
1087 if (!to->requests[i].buf)
1089 if (i == MAX_REQUESTS) {
1090 for (i = 0; i < to->nextid; i++)
1091 if (!to->requests[i].buf)
1093 if (i == to->nextid) {
1094 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
1100 rq->buf[1] = (char)i;
1102 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1103 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1108 if (*(uint8_t *)rq->buf == RAD_Accounting_Request) {
1109 if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
1110 debug(DBG_WARN, "sendrq: failed to sign Accounting-Request message");
1116 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1117 to->requests[i] = *rq;
1122 debug(DBG_DBG, "sendrq: signalling client writer");
1123 pthread_cond_signal(&to->newrq_cond);
1126 pthread_mutex_unlock(&to->newrq_mutex);
1129 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
1130 struct reply *reply;
1133 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1135 debug(DBG_WARN, "sendreply: failed to sign message");
1139 reply = malloc(sizeof(struct reply));
1142 debug(DBG_ERR, "sendreply: malloc failed");
1145 memset(reply, 0, sizeof(struct reply));
1148 reply->tosa = *tosa;
1150 pthread_mutex_lock(&to->replyq->mutex);
1152 first = list_first(to->replyq->replies) == NULL;
1154 if (!list_push(to->replyq->replies, reply)) {
1155 pthread_mutex_unlock(&to->replyq->mutex);
1158 debug(DBG_ERR, "sendreply: malloc failed");
1163 debug(DBG_DBG, "signalling server writer");
1164 pthread_cond_signal(&to->replyq->cond);
1166 pthread_mutex_unlock(&to->replyq->mutex);
1169 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1170 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1171 static unsigned char first = 1;
1172 static EVP_MD_CTX mdctx;
1173 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1174 unsigned int md_len;
1175 uint8_t i, offset = 0, out[128];
1177 pthread_mutex_lock(&lock);
1179 EVP_MD_CTX_init(&mdctx);
1185 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1186 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1187 !EVP_DigestUpdate(&mdctx, input, 16) ||
1188 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1190 pthread_mutex_unlock(&lock);
1193 for (i = 0; i < 16; i++)
1194 out[offset + i] = hash[i] ^ in[offset + i];
1195 input = out + offset - 16;
1200 memcpy(in, out, len);
1201 pthread_mutex_unlock(&lock);
1205 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1206 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1207 static unsigned char first = 1;
1208 static EVP_MD_CTX mdctx;
1209 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1210 unsigned int md_len;
1211 uint8_t i, offset = 0, out[128];
1213 pthread_mutex_lock(&lock);
1215 EVP_MD_CTX_init(&mdctx);
1221 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1222 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1223 !EVP_DigestUpdate(&mdctx, input, 16) ||
1224 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1226 pthread_mutex_unlock(&lock);
1229 for (i = 0; i < 16; i++)
1230 out[offset + i] = hash[i] ^ in[offset + i];
1231 input = in + offset;
1236 memcpy(in, out, len);
1237 pthread_mutex_unlock(&lock);
1241 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1242 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1243 static unsigned char first = 1;
1244 static EVP_MD_CTX mdctx;
1245 unsigned char hash[EVP_MAX_MD_SIZE];
1246 unsigned int md_len;
1249 pthread_mutex_lock(&lock);
1251 EVP_MD_CTX_init(&mdctx);
1256 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1257 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1258 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1261 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1262 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1263 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1264 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1265 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1266 pthread_mutex_unlock(&lock);
1271 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1274 for (i = 0; i < 16; i++)
1277 for (offset = 16; offset < len; offset += 16) {
1279 printf("text + offset - 16 c(%d): ", offset / 16);
1280 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1282 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1283 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1284 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1285 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1287 pthread_mutex_unlock(&lock);
1291 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1294 for (i = 0; i < 16; i++)
1295 text[offset + i] ^= hash[i];
1299 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1302 pthread_mutex_unlock(&lock);
1306 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1307 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1308 static unsigned char first = 1;
1309 static EVP_MD_CTX mdctx;
1310 unsigned char hash[EVP_MAX_MD_SIZE];
1311 unsigned int md_len;
1315 pthread_mutex_lock(&lock);
1317 EVP_MD_CTX_init(&mdctx);
1322 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1323 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1324 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1327 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1328 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1329 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1330 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1331 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1332 pthread_mutex_unlock(&lock);
1337 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1340 for (i = 0; i < 16; i++)
1341 plain[i] = text[i] ^ hash[i];
1343 for (offset = 16; offset < len; offset += 16) {
1345 printf("text + offset - 16 c(%d): ", offset / 16);
1346 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1348 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1349 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1350 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1351 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1353 pthread_mutex_unlock(&lock);
1357 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1360 for (i = 0; i < 16; i++)
1361 plain[offset + i] = text[offset + i] ^ hash[i];
1364 memcpy(text, plain, len);
1366 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1369 pthread_mutex_unlock(&lock);
1373 struct realm *id2realm(char *id, uint8_t len) {
1374 struct list_node *entry;
1375 struct realm *realm;
1377 for (entry = list_first(realms); entry; entry = list_next(entry)) {
1378 realm = (struct realm *)entry->data;
1379 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1380 debug(DBG_DBG, "found matching realm: %s", realm->name);
1387 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1388 struct request *rq = to->requests, *end;
1390 pthread_mutex_lock(&to->newrq_mutex);
1391 for (end = rq + MAX_REQUESTS; rq < end; rq++)
1392 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1394 pthread_mutex_unlock(&to->newrq_mutex);
1399 int attrvalidate(unsigned char *attrs, int length) {
1400 while (length > 1) {
1401 if (ATTRLEN(attrs) < 2) {
1402 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1405 length -= ATTRLEN(attrs);
1407 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1410 attrs += ATTRLEN(attrs);
1413 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1417 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1418 if (len < 16 || len > 128 || len % 16) {
1419 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1423 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1424 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1428 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1430 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1431 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1437 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1440 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1441 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1444 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1445 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1451 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1452 char *oldsecret, char *newsecret) {
1453 unsigned char *attr;
1455 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1456 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1457 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1463 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1467 for (; attrs[0]; attrs += 2)
1468 if (attrs[0] == vendor && attrs[1] == subattr)
1473 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1474 uint8_t alen, sublen, rmlen = 0;
1478 if (!removevendorattrs)
1481 memcpy(&vendor, ATTRVAL(attrs), 4);
1482 vendor = ntohl(vendor);
1483 while (*removevendorattrs && *removevendorattrs != vendor)
1484 removevendorattrs += 2;
1485 if (!*removevendorattrs)
1488 alen = ATTRLEN(attrs);
1490 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1491 /* remove entire vendor attribute */
1492 memmove(attrs, attrs + alen, length - alen);
1497 subattrs = ATTRVAL(attrs) + 4;
1499 if (!attrvalidate(subattrs, sublen)) {
1500 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1505 while (sublen > 1) {
1506 alen = ATTRLEN(subattrs);
1509 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1510 memmove(subattrs, subattrs + alen, length);
1516 ATTRLEN(attrs) -= rmlen;
1520 void dorewriterm(uint8_t *buf, uint8_t *rmattrs, uint32_t *rmvattrs) {
1521 uint8_t *attrs, alen;
1522 uint16_t len, rmlen = 0;
1524 len = RADLEN(buf) - 20;
1527 alen = ATTRLEN(attrs);
1529 if (rmattrs && strchr((char *)rmattrs, ATTRTYPE(attrs))) {
1530 memmove(attrs, attrs + alen, len);
1532 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rmvattrs)
1533 rmlen += dovendorrewrite(attrs, len, rmvattrs);
1538 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1541 int dorewriteadd(uint8_t **buf, struct list *addattrs) {
1542 struct list_node *n;
1543 struct attribute *a;
1544 uint16_t i, addlen = 0;
1547 for (n = list_first(addattrs); n; n = list_next(n))
1548 addlen += 2 + ((struct attribute *)n->data)->l;
1551 newbuf = realloc(*buf, RADLEN(*buf) + addlen);
1556 for (n = list_first(addattrs); n; n = list_next(n)) {
1557 a = (struct attribute *)n->data;
1559 newbuf[i++] = a->l + 2;
1560 memcpy(newbuf + i, a->v, a->l);
1563 ((uint16_t *)newbuf)[1] = htons(RADLEN(newbuf) + addlen);
1568 /* returns a pointer to the resized attribute value */
1569 uint8_t *resizeattr(uint8_t **buf, uint8_t **attr, uint8_t newvallen) {
1574 vallen = ATTRVALLEN(*attr);
1575 if (vallen == newvallen)
1578 len = RADLEN(*buf) + newvallen - vallen;
1580 if (newvallen > vallen) {
1581 new = realloc(*buf, len);
1583 debug(DBG_ERR, "resizeattr: malloc failed");
1587 *attr += new - *buf;
1592 memmove(*attr + 2 + newvallen, *attr + 2 + vallen, len - (*attr - *buf + newvallen + 2));
1593 (*attr)[1] = newvallen + 2;
1594 ((uint16_t *)*buf)[1] = htons(len);
1598 int dorewritemodattr(uint8_t **buf, uint8_t **attr, struct modattr *modattr) {
1599 size_t nmatch = 10, reslen = 0, start = 0;
1600 regmatch_t pmatch[10], *pfield;
1602 unsigned char *result;
1605 in = stringcopy((char *)ATTRVAL(*attr), ATTRVALLEN(*attr));
1609 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1614 out = modattr->replacement;
1616 for (i = start; out[i]; i++) {
1617 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1618 pfield = &pmatch[out[i + 1] - '0'];
1619 if (pfield->rm_so >= 0) {
1620 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1626 reslen += i - start;
1628 debug(DBG_WARN, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1632 result = resizeattr(buf, attr, reslen);
1640 for (i = start; out[i]; i++) {
1641 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1642 pfield = &pmatch[out[i + 1] - '0'];
1643 if (pfield->rm_so >= 0) {
1644 memcpy(result + reslen, out + start, i - start);
1645 reslen += i - start;
1646 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1647 reslen += pfield->rm_eo - pfield->rm_so;
1654 memcpy(result + reslen, out + start, i - start);
1658 int dorewritemod(uint8_t **buf, struct list *modattrs) {
1661 struct list_node *n;
1664 while (RADLEN(*buf) - 22 >= len) {
1665 for (n = list_first(modattrs); n; n = list_next(n))
1666 if (ATTRTYPE(attr) == ((struct modattr *)n->data)->t)
1667 if (!dorewritemodattr(buf, &attr, (struct modattr *)n->data))
1669 len += ATTRLEN(attr);
1670 attr += ATTRLEN(attr);
1675 int dorewrite(uint8_t **buf, struct rewrite *rewrite) {
1678 if (rewrite->removeattrs || rewrite->removevendorattrs)
1679 dorewriterm(*buf, rewrite->removeattrs, rewrite->removevendorattrs);
1680 if (rewrite->addattrs && !dorewriteadd(buf, rewrite->addattrs))
1682 if (rewrite->modattrs && !dorewritemod(buf, rewrite->modattrs))
1687 int rewriteusername(struct request *rq, uint8_t *attr, char *in) {
1688 if (!dorewritemodattr(&rq->buf, &attr, rq->from->conf->rewriteusername))
1690 if (strlen(in) == ATTRVALLEN(attr) && !memcmp(in, ATTRVAL(attr), ATTRVALLEN(attr)))
1693 rq->origusername = stringcopy(in, 0);
1694 if (!rq->origusername)
1697 memcpy(in, ATTRVAL(attr), ATTRVALLEN(attr));
1698 in[ATTRVALLEN(attr)] = '\0';
1702 const char *radmsgtype2string(uint8_t code) {
1703 static const char *rad_msg_names[] = {
1704 "", "Access-Request", "Access-Accept", "Access-Reject",
1705 "Accounting-Request", "Accounting-Response", "", "",
1706 "", "", "", "Access-Challenge",
1707 "Status-Server", "Status-Client"
1709 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1712 void char2hex(char *h, unsigned char c) {
1713 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1714 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1715 h[0] = hexdigits[c / 16];
1716 h[1] = hexdigits[c % 16];
1720 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
1724 if (!attr || len == 1) {
1729 l = ATTRVALLEN(attr);
1730 s = (char *)ATTRVAL(attr);
1733 for (i = 0; i < l; i++) {
1734 if (s[i] > 31 && s[i] < 127) {
1736 if (d - ascii == len - 1)
1739 if (d - ascii > len - 4)
1744 if (d - ascii == len - 1)
1752 void acclog(unsigned char *attrs, int length, char *host) {
1753 unsigned char *attr;
1756 attr = attrget(attrs, length, RAD_Attr_User_Name);
1758 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1761 radattr2ascii(username, sizeof(username), attr);
1762 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1765 void respondaccounting(struct request *rq) {
1766 unsigned char *resp;
1770 debug(DBG_ERR, "respondstatusserver: malloc failed");
1773 memcpy(resp, rq->buf, 20);
1774 resp[0] = RAD_Accounting_Response;
1777 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1778 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1781 void respondstatusserver(struct request *rq) {
1782 unsigned char *resp;
1786 debug(DBG_ERR, "respondstatusserver: malloc failed");
1789 memcpy(resp, rq->buf, 20);
1790 resp[0] = RAD_Access_Accept;
1793 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1794 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1797 void respondreject(struct request *rq, char *message) {
1798 unsigned char *resp;
1801 if (message && *message)
1802 len += 2 + strlen(message);
1806 debug(DBG_ERR, "respondreject: malloc failed");
1809 memcpy(resp, rq->buf, 20);
1810 resp[0] = RAD_Access_Reject;
1811 *(uint16_t *)(resp + 2) = htons(len);
1812 if (message && *message) {
1813 resp[20] = RAD_Attr_Reply_Message;
1814 resp[21] = len - 20;
1815 memcpy(resp + 22, message, len - 22);
1817 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1820 struct server *chooseserver(struct list *srvconfs) {
1821 struct list_node *entry;
1822 struct server *server, *best = NULL, *first = NULL;
1824 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1825 server = ((struct clsrvconf *)entry->data)->servers;
1828 if (!server->connectionok)
1830 if (!server->lostrqs)
1836 if (server->lostrqs < best->lostrqs)
1839 return best ? best : first;
1842 void radsrv(struct request *rq) {
1843 uint8_t code, id, *auth, *attrs, *attr;
1845 struct server *to = NULL;
1846 char username[254], userascii[760];
1847 unsigned char newauth[16];
1848 struct realm *realm = NULL;
1850 code = *(uint8_t *)rq->buf;
1851 id = *(uint8_t *)(rq->buf + 1);
1852 len = RADLEN(rq->buf);
1853 auth = (uint8_t *)(rq->buf + 4);
1855 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1857 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1858 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1863 attrs = rq->buf + 20;
1865 if (!attrvalidate(attrs, len)) {
1866 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1870 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1871 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
1872 debug(DBG_WARN, "radsrv: message authentication failed");
1876 if (code == RAD_Status_Server) {
1877 respondstatusserver(rq);
1881 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1883 if (code == RAD_Accounting_Request) {
1884 memset(newauth, 0, 16);
1885 if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
1886 debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
1891 if (rq->from->conf->rewritein) {
1892 if (!dorewrite(&rq->buf, rq->from->conf->rewritein))
1894 len = RADLEN(rq->buf) - 20;
1895 auth = (uint8_t *)(rq->buf + 4);
1896 attrs = rq->buf + 20;
1899 attr = attrget(attrs, len, RAD_Attr_User_Name);
1901 if (code == RAD_Accounting_Request) {
1902 acclog(attrs, len, rq->from->conf->host);
1903 respondaccounting(rq);
1905 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1908 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1909 username[ATTRVALLEN(attr)] = '\0';
1910 radattr2ascii(userascii, sizeof(userascii), attr);
1912 if (rq->from->conf->rewriteusername) {
1913 if (!rewriteusername(rq, attr, username)) {
1914 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1917 len = RADLEN(rq->buf) - 20;
1918 auth = (uint8_t *)(rq->buf + 4);
1919 attrs = rq->buf + 20;
1922 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
1924 realm = id2realm(username, strlen(username));
1926 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1930 to = chooseserver(code == RAD_Access_Request ? realm->srvconfs : realm->accsrvconfs);
1932 if (realm->message && code == RAD_Access_Request) {
1933 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
1934 respondreject(rq, realm->message);
1935 } else if (realm->accresp && code == RAD_Accounting_Request) {
1936 acclog(attrs, len, rq->from->conf->host);
1937 respondaccounting(rq);
1942 if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
1943 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
1944 rq->from->conf->name, to->conf->name);
1948 if (rqinqueue(to, rq->from, id, code)) {
1949 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
1950 radmsgtype2string(code), rq->from->conf->host, id);
1954 if (code != RAD_Accounting_Request) {
1955 if (!RAND_bytes(newauth, 16)) {
1956 debug(DBG_WARN, "radsrv: failed to generate random auth");
1962 printfchars(NULL, "auth", "%02x ", auth, 16);
1965 attr = attrget(attrs, len, RAD_Attr_User_Password);
1967 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1968 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
1972 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1974 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1975 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
1980 memcpy(rq->origauth, auth, 16);
1981 memcpy(auth, newauth, 16);
1983 if (to->conf->rewriteout)
1984 if (!dorewrite(&rq->buf, to->conf->rewriteout))
1994 int replyh(struct server *server, unsigned char *buf) {
1995 struct client *from;
1998 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
1999 struct sockaddr_storage fromsa;
2000 char tmp[760], stationid[760], replymsg[760];
2002 server->connectionok = 1;
2003 server->lostrqs = 0;
2005 i = buf[1]; /* i is the id */
2007 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
2008 && *buf != RAD_Accounting_Response) {
2009 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
2012 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
2014 rq = server->requests + i;
2016 pthread_mutex_lock(&server->newrq_mutex);
2017 if (!rq->buf || !rq->tries) {
2018 pthread_mutex_unlock(&server->newrq_mutex);
2019 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
2024 pthread_mutex_unlock(&server->newrq_mutex);
2025 debug(DBG_INFO, "replyh: already received, ignoring reply");
2029 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
2030 pthread_mutex_unlock(&server->newrq_mutex);
2031 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
2035 len = RADLEN(buf) - 20;
2038 if (!attrvalidate(attrs, len)) {
2039 pthread_mutex_unlock(&server->newrq_mutex);
2040 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
2044 /* Message Authenticator */
2045 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2047 if (ATTRVALLEN(messageauth) != 16) {
2048 pthread_mutex_unlock(&server->newrq_mutex);
2049 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
2052 memcpy(tmp, buf + 4, 16);
2053 memcpy(buf + 4, rq->buf + 4, 16);
2054 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
2055 pthread_mutex_unlock(&server->newrq_mutex);
2056 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
2059 memcpy(buf + 4, tmp, 16);
2060 debug(DBG_DBG, "replyh: message auth ok");
2063 if (*rq->buf == RAD_Status_Server) {
2065 pthread_mutex_unlock(&server->newrq_mutex);
2066 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2072 pthread_mutex_unlock(&server->newrq_mutex);
2073 debug(DBG_INFO, "replyh: client gone, ignoring reply");
2077 if (server->conf->rewritein) {
2078 if (!dorewrite(&buf, server->conf->rewritein))
2080 len = RADLEN(buf) - 20;
2083 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2087 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2088 if (ATTRVALLEN(attr) <= 4)
2091 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
2094 sublen = ATTRVALLEN(attr) - 4;
2095 subattrs = ATTRVAL(attr) + 4;
2096 if (!attrvalidate(subattrs, sublen) ||
2097 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2098 rq, server->conf->secret, from->conf->secret) ||
2099 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2100 rq, server->conf->secret, from->conf->secret))
2104 pthread_mutex_unlock(&server->newrq_mutex);
2105 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2109 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2110 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2112 radattr2ascii(tmp, sizeof(tmp), attr);
2113 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2115 radattr2ascii(stationid, sizeof(stationid), attr);
2116 attr = attrget(buf + 20, RADLEN(buf) - 20, RAD_Attr_Reply_Message);
2118 radattr2ascii(replymsg, sizeof(replymsg), attr);
2119 debug(DBG_INFO, "%s for user %s stationid %s from %s (%s)",
2120 radmsgtype2string(*buf), tmp, stationid, server->conf->host, replymsg);
2122 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2123 radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2125 attr = attrget(buf + 20, RADLEN(buf) - 20, RAD_Attr_Reply_Message);
2127 radattr2ascii(replymsg, sizeof(replymsg), attr);
2128 debug(DBG_INFO, "%s for user %s from %s (%s)",
2129 radmsgtype2string(*buf), tmp, server->conf->host, replymsg);
2131 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2136 buf[1] = (char)rq->origid;
2137 memcpy(buf + 4, rq->origauth, 16);
2139 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2142 if (rq->origusername && (attr = attrget(buf + 20, RADLEN(buf) - 20, RAD_Attr_User_Name))) {
2143 username = resizeattr(&buf, &attr, strlen(rq->origusername));
2145 pthread_mutex_unlock(&server->newrq_mutex);
2146 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2149 memcpy(username, rq->origusername, strlen(rq->origusername));
2150 len = RADLEN(buf) - 20;
2153 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2156 if (from->conf->rewriteout) {
2157 if (!dorewrite(&buf, from->conf->rewriteout))
2159 len = RADLEN(buf) - 20;
2162 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2166 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2167 pthread_mutex_unlock(&server->newrq_mutex);
2168 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2171 debug(DBG_DBG, "replyh: computed messageauthattr");
2174 if (from->conf->type == 'U')
2175 fromsa = rq->fromsa;
2176 /* once we set received = 1, rq may be reused */
2179 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2180 sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
2181 pthread_mutex_unlock(&server->newrq_mutex);
2185 void *udpclientrd(void *arg) {
2186 struct server *server;
2188 int *s = (int *)arg;
2192 buf = radudpget(*s, NULL, &server, NULL);
2193 if (!replyh(server, buf))
2198 void *tlsclientrd(void *arg) {
2199 struct server *server = (struct server *)arg;
2201 struct timeval lastconnecttry;
2204 /* yes, lastconnecttry is really necessary */
2205 lastconnecttry = server->lastconnecttry;
2206 buf = radtlsget(server->ssl);
2208 tlsconnect(server, &lastconnecttry, "clientrd");
2212 if (!replyh(server, buf))
2217 void *clientwr(void *arg) {
2218 struct server *server = (struct server *)arg;
2220 pthread_t tlsclientrdth;
2223 struct timeval now, lastsend;
2224 struct timespec timeout;
2225 struct request statsrvrq;
2226 unsigned char statsrvbuf[38];
2228 memset(&timeout, 0, sizeof(struct timespec));
2230 if (server->conf->statusserver) {
2231 memset(&statsrvrq, 0, sizeof(struct request));
2232 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2233 statsrvbuf[0] = RAD_Status_Server;
2235 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2236 statsrvbuf[21] = 18;
2237 gettimeofday(&lastsend, NULL);
2240 if (server->conf->type == 'U') {
2241 server->connectionok = 1;
2243 tlsconnect(server, NULL, "new client");
2244 server->connectionok = 1;
2245 if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server))
2246 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
2250 pthread_mutex_lock(&server->newrq_mutex);
2251 if (!server->newrq) {
2252 gettimeofday(&now, NULL);
2253 if (server->conf->statusserver) {
2254 /* random 0-7 seconds */
2255 RAND_bytes(&rnd, 1);
2257 if (!timeout.tv_sec || timeout.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
2258 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
2260 if (timeout.tv_sec) {
2261 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2262 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2265 debug(DBG_DBG, "clientwr: waiting for new request");
2266 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
2269 if (server->newrq) {
2270 debug(DBG_DBG, "clientwr: got new request");
2273 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2274 pthread_mutex_unlock(&server->newrq_mutex);
2276 for (i = 0; i < MAX_REQUESTS; i++) {
2277 pthread_mutex_lock(&server->newrq_mutex);
2278 while (i < MAX_REQUESTS && !server->requests[i].buf)
2280 if (i == MAX_REQUESTS) {
2281 pthread_mutex_unlock(&server->newrq_mutex);
2284 rq = server->requests + i;
2287 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2289 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2291 /* setting this to NULL means that it can be reused */
2294 pthread_mutex_unlock(&server->newrq_mutex);
2298 gettimeofday(&now, NULL);
2299 if (now.tv_sec < rq->expiry.tv_sec) {
2300 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2301 timeout.tv_sec = rq->expiry.tv_sec;
2302 pthread_mutex_unlock(&server->newrq_mutex);
2306 if (rq->tries == (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
2307 ? 1 : server->conf->retrycount + 1)) {
2308 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2309 if (server->conf->statusserver) {
2310 if (*rq->buf == RAD_Status_Server) {
2311 debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->conf->host);
2312 if (server->lostrqs < 255)
2316 debug(DBG_WARN, "clientwr: no server response, %s dead?", server->conf->host);
2317 if (server->lostrqs < 255)
2321 /* setting this to NULL means that it can be reused */
2323 pthread_mutex_unlock(&server->newrq_mutex);
2326 pthread_mutex_unlock(&server->newrq_mutex);
2328 rq->expiry.tv_sec = now.tv_sec +
2329 (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
2330 ? server->conf->retryinterval * (server->conf->retrycount + 1) : server->conf->retryinterval);
2331 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2332 timeout.tv_sec = rq->expiry.tv_sec;
2334 clientradput(server, server->requests[i].buf);
2335 gettimeofday(&lastsend, NULL);
2337 if (server->conf->statusserver) {
2338 gettimeofday(&now, NULL);
2339 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
2340 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2341 debug(DBG_WARN, "clientwr: failed to generate random auth");
2344 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2345 if (!statsrvrq.buf) {
2346 debug(DBG_ERR, "clientwr: malloc failed");
2349 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2350 debug(DBG_DBG, "clientwr: sending status server to %s", server->conf->host);
2351 lastsend.tv_sec = now.tv_sec;
2352 sendrq(server, &statsrvrq);
2358 void *udpserverwr(void *arg) {
2359 struct replyq *replyq = udp_server_replyq;
2360 struct reply *reply;
2363 pthread_mutex_lock(&replyq->mutex);
2364 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2365 debug(DBG_DBG, "udp server writer, waiting for signal");
2366 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2367 debug(DBG_DBG, "udp server writer, got signal");
2369 pthread_mutex_unlock(&replyq->mutex);
2371 if (sendto(*(uint8_t *)reply->buf == RAD_Accounting_Response ? udp_accserver_sock : udp_server_sock,
2372 reply->buf, RADLEN(reply->buf), 0,
2373 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2374 debug(DBG_WARN, "sendudp: send failed");
2380 void *udpserverrd(void *arg) {
2382 pthread_t udpserverwrth;
2383 struct clsrvconf *listenres;
2385 listenres = resolve_hostport('U', options.listenudp, DEFAULT_UDP_PORT);
2386 if ((udp_server_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2387 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2389 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
2390 listenres->host ? listenres->host : "*", listenres->port);
2391 freeclsrvres(listenres);
2393 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
2394 debugx(1, DBG_ERR, "pthread_create failed");
2397 memset(&rq, 0, sizeof(struct request));
2398 rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
2403 void *udpaccserverrd(void *arg) {
2405 struct clsrvconf *listenres;
2407 listenres = resolve_hostport('U', options.listenaccudp, DEFAULT_UDP_PORT);
2408 if ((udp_accserver_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2409 debugx(1, DBG_ERR, "udpaccserverrd: socket/bind failed");
2411 debug(DBG_WARN, "udpaccserverrd: listening for UDP on %s:%s",
2412 listenres->host ? listenres->host : "*", listenres->port);
2413 freeclsrvres(listenres);
2416 memset(&rq, 0, sizeof(struct request));
2417 rq.buf = radudpget(udp_accserver_sock, &rq.from, NULL, &rq.fromsa);
2418 if (*rq.buf == RAD_Accounting_Request || *rq.buf == RAD_Status_Server) {
2422 debug(DBG_INFO, "udpaccserverrd: accepting only accounting-request and status-server, ignoring");
2427 void *tlsserverwr(void *arg) {
2429 unsigned long error;
2430 struct client *client = (struct client *)arg;
2431 struct replyq *replyq;
2432 struct reply *reply;
2434 debug(DBG_DBG, "tlsserverwr starting for %s", addr2string(client->addr));
2436 replyq = client->replyq;
2438 pthread_mutex_lock(&replyq->mutex);
2439 while (!list_first(replyq->replies)) {
2441 debug(DBG_DBG, "tls server writer, waiting for signal");
2442 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2443 debug(DBG_DBG, "tls server writer, got signal");
2446 /* ssl might have changed while waiting */
2447 pthread_mutex_unlock(&replyq->mutex);
2448 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2449 ERR_remove_state(0);
2453 reply = (struct reply *)list_shift(replyq->replies);
2454 pthread_mutex_unlock(&replyq->mutex);
2455 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2457 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d to %s",
2458 cnt, RADLEN(reply->buf), addr2string(client->addr));
2460 while ((error = ERR_get_error()))
2461 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2467 void tlsserverrd(struct client *client) {
2469 pthread_t tlsserverwrth;
2471 debug(DBG_DBG, "tlsserverrd starting for %s", addr2string(client->addr));
2473 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2474 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2479 memset(&rq, 0, sizeof(struct request));
2480 rq.buf = radtlsget(client->ssl);
2483 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", addr2string(client->addr));
2488 debug(DBG_ERR, "tlsserverrd: connection from %s lost", addr2string(client->addr));
2489 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2491 pthread_mutex_lock(&client->replyq->mutex);
2492 pthread_cond_signal(&client->replyq->cond);
2493 pthread_mutex_unlock(&client->replyq->mutex);
2494 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2495 pthread_join(tlsserverwrth, NULL);
2496 removeclientrqs(client);
2497 debug(DBG_DBG, "tlsserverrd for %s exiting", addr2string(client->addr));
2500 void *tlsservernew(void *arg) {
2502 struct sockaddr_storage from;
2503 size_t fromlen = sizeof(from);
2504 struct clsrvconf *conf;
2505 struct list_node *cur = NULL;
2508 unsigned long error;
2509 struct client *client;
2512 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
2513 debug(DBG_DBG, "tlsservernew: getpeername failed, exiting");
2516 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from));
2518 conf = find_conf('T', (struct sockaddr *)&from, clconfs, &cur);
2520 ssl = SSL_new(conf->ssl_ctx);
2523 if (SSL_accept(ssl) <= 0) {
2524 while ((error = ERR_get_error()))
2525 debug(DBG_ERR, "tlsservernew: SSL: %s", ERR_error_string(error, NULL));
2526 debug(DBG_ERR, "tlsservernew: SSL_accept failed");
2529 cert = verifytlscert(ssl);
2535 if (verifyconfcert(cert, conf)) {
2537 client = addclient(conf);
2540 client->addr = addr_copy((struct sockaddr *)&from);
2541 tlsserverrd(client);
2542 removeclient(client);
2544 debug(DBG_WARN, "Failed to create new client instance");
2547 conf = find_conf('T', (struct sockaddr *)&from, clconfs, &cur);
2549 debug(DBG_WARN, "ignoring request, no matching TLS client");
2558 ERR_remove_state(0);
2559 shutdown(s, SHUT_RDWR);
2565 pthread_t tlsserverth;
2567 struct sockaddr_storage from;
2568 size_t fromlen = sizeof(from);
2569 struct clsrvconf *listenres;
2571 listenres = resolve_hostport('T', options.listentcp, DEFAULT_TLS_PORT);
2572 if ((s = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2573 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
2575 debug(DBG_WARN, "listening for incoming TCP on %s:%s", listenres->host ? listenres->host : "*", listenres->port);
2576 freeclsrvres(listenres);
2580 snew = accept(s, (struct sockaddr *)&from, &fromlen);
2582 debug(DBG_WARN, "accept failed");
2585 if (pthread_create(&tlsserverth, NULL, tlsservernew, (void *)&snew)) {
2586 debug(DBG_ERR, "tlslistener: pthread_create failed");
2587 shutdown(snew, SHUT_RDWR);
2591 pthread_detach(tlsserverth);
2596 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd, uint8_t crlcheck) {
2599 STACK_OF(X509_NAME) *calist;
2602 unsigned long error;
2604 if (!certfile || !certkeyfile)
2605 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2607 if (!cacertfile && !cacertpath)
2608 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2611 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2612 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2613 for (i = 0; i < CRYPTO_num_locks(); i++) {
2614 ssl_lock_count[i] = 0;
2615 pthread_mutex_init(&ssl_locks[i], NULL);
2617 CRYPTO_set_id_callback(ssl_thread_id);
2618 CRYPTO_set_locking_callback(ssl_locking_callback);
2620 SSL_load_error_strings();
2623 while (!RAND_status()) {
2624 time_t t = time(NULL);
2625 pid_t pid = getpid();
2626 RAND_seed((unsigned char *)&t, sizeof(time_t));
2627 RAND_seed((unsigned char *)&pid, sizeof(pid));
2630 ctx = SSL_CTX_new(TLSv1_method());
2632 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2633 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2635 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2636 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2637 !SSL_CTX_check_private_key(ctx) ||
2638 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2639 while ((error = ERR_get_error()))
2640 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2641 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2644 calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
2645 if (!cacertfile || calist) {
2648 calist = sk_X509_NAME_new_null();
2649 if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
2650 sk_X509_NAME_free(calist);
2656 while ((error = ERR_get_error()))
2657 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2658 debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
2660 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2661 SSL_CTX_set_client_CA_list(ctx, calist);
2663 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2664 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2667 x509_s = SSL_CTX_get_cert_store(ctx);
2668 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2671 new = malloc(sizeof(struct tls));
2672 if (!new || !list_push(tlsconfs, new))
2673 debugx(1, DBG_ERR, "malloc failed");
2675 memset(new, 0, sizeof(struct tls));
2676 new->name = stringcopy(value, 0);
2678 debugx(1, DBG_ERR, "malloc failed");
2681 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2685 struct list_node *entry;
2688 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2689 t = (struct tls *)entry->data;
2693 SSL_CTX_free(t->ctx);
2695 list_destroy(tlsconfs);
2699 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2700 struct list_node *entry;
2701 struct tls *t, *t1 = NULL, *t2 = NULL;
2703 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2704 t = (struct tls *)entry->data;
2705 if (!strcasecmp(t->name, alt1)) {
2709 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2720 struct list *addsrvconfs(char *value, char **names) {
2721 struct list *conflist;
2723 struct list_node *entry;
2724 struct clsrvconf *conf = NULL;
2726 if (!names || !*names)
2729 conflist = list_create();
2731 debugx(1, DBG_ERR, "malloc failed");
2733 for (n = 0; names[n]; n++) {
2734 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2735 conf = (struct clsrvconf *)entry->data;
2736 if (!strcasecmp(names[n], conf->name))
2740 debugx(1, DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2742 if (!list_push(conflist, conf))
2743 debugx(1, DBG_ERR, "malloc failed");
2744 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2750 void addrealm(char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2752 struct realm *realm;
2753 char *s, *regex = NULL;
2755 if (*value == '/') {
2756 /* regexp, remove optional trailing / if present */
2757 if (value[strlen(value) - 1] == '/')
2758 value[strlen(value) - 1] = '\0';
2760 /* not a regexp, let us make it one */
2761 if (*value == '*' && !value[1])
2762 regex = stringcopy(".*", 0);
2764 for (n = 0, s = value; *s;)
2767 regex = malloc(strlen(value) + n + 3);
2770 for (n = 1, s = value; *s; s++) {
2780 debugx(1, DBG_ERR, "malloc failed");
2781 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2784 realm = malloc(sizeof(struct realm));
2786 debugx(1, DBG_ERR, "malloc failed");
2788 memset(realm, 0, sizeof(struct realm));
2789 realm->name = stringcopy(value, 0);
2791 debugx(1, DBG_ERR, "malloc failed");
2792 if (message && strlen(message) > 253)
2793 debugx(1, DBG_ERR, "ReplyMessage can be at most 253 bytes");
2794 realm->message = message;
2795 realm->accresp = accresp;
2797 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB))
2798 debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2802 realm->srvconfs = addsrvconfs(value, servers);
2803 realm->accsrvconfs = addsrvconfs(value, accservers);
2805 if (!list_push(realms, realm))
2806 debugx(1, DBG_ERR, "malloc failed");
2807 debug(DBG_DBG, "addrealm: added realm %s", value);
2810 int addmatchcertattr(struct clsrvconf *conf, char *matchcertattr) {
2814 if (!strncasecmp(matchcertattr, "CN:/", 4)) {
2815 r = &conf->certcnregex;
2816 v = matchcertattr + 4;
2817 } else if (!strncasecmp(matchcertattr, "SubjectAltName:URI:/", 20)) {
2818 r = &conf->certuriregex;
2819 v = matchcertattr + 20;
2824 /* regexp, remove optional trailing / if present */
2825 if (v[strlen(v) - 1] == '/')
2826 v[strlen(v) - 1] = '\0';
2830 *r = malloc(sizeof(regex_t));
2832 debug(DBG_ERR, "malloc failed");
2835 if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2838 debug(DBG_ERR, "failed to compile regular expression %s", v);
2844 /* should accept both names and numeric values, only numeric right now */
2845 uint8_t attrname2val(char *attrname) {
2848 val = atoi(attrname);
2849 return val > 0 && val < 256 ? val : 0;
2852 /* should accept both names and numeric values, only numeric right now */
2853 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2856 *vendor = atoi(attrname);
2857 s = strchr(attrname, ':');
2862 *type = atoi(s + 1);
2863 return *type >= 0 && *type < 256;
2866 /* should accept both names and numeric values, only numeric right now */
2867 struct attribute *extractattr(char *nameval) {
2870 struct attribute *a;
2872 s = strchr(nameval, ':');
2873 name = atoi(nameval);
2874 if (!s || name < 1 || name > 255)
2876 len = strlen(s + 1);
2879 a = malloc(sizeof(struct attribute));
2882 a->v = (uint8_t *)stringcopy(s + 1, 0);
2892 /* should accept both names and numeric values, only numeric right now */
2893 struct modattr *extractmodattr(char *nameval) {
2898 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2902 s = strchr(nameval, ':');
2903 name = atoi(nameval);
2904 if (!s || name < 1 || name > 255 || s[1] != '/')
2908 /* regexp, remove optional trailing / if present */
2909 if (s[strlen(s) - 1] == '/')
2910 s[strlen(s) - 1] = '\0';
2918 m = malloc(sizeof(struct modattr));
2920 debug(DBG_ERR, "malloc failed");
2925 m->replacement = stringcopy(t, 0);
2926 if (!m->replacement) {
2928 debug(DBG_ERR, "malloc failed");
2932 m->regex = malloc(sizeof(regex_t));
2934 free(m->replacement);
2936 debug(DBG_ERR, "malloc failed");
2940 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2942 free(m->replacement);
2944 debug(DBG_ERR, "failed to compile regular expression %s", s);
2951 void rewritefree() {
2952 struct list_node *entry;
2953 struct rewriteconf *r;
2955 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
2956 r = (struct rewriteconf *)entry->data;
2962 list_destroy(rewriteconfs);
2963 rewriteconfs = NULL;
2966 struct rewrite *getrewrite(char *alt1, char *alt2) {
2967 struct list_node *entry;
2968 struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
2970 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
2971 r = (struct rewriteconf *)entry->data;
2972 if (!strcasecmp(r->name, alt1)) {
2976 if (!r2 && alt2 && !strcasecmp(r->name, alt2))
2987 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
2988 struct rewriteconf *new;
2989 struct rewrite *rewrite = NULL;
2991 uint8_t *rma = NULL;
2992 uint32_t *p, *rmva = NULL;
2993 struct list *adda = NULL, *moda = NULL;
2994 struct attribute *a;
2998 for (n = 0; rmattrs[n]; n++);
2999 rma = calloc(n + 1, sizeof(uint8_t));
3001 debugx(1, DBG_ERR, "malloc failed");
3003 for (i = 0; i < n; i++) {
3004 if (!(rma[i] = attrname2val(rmattrs[i])))
3005 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
3013 for (n = 0; rmvattrs[n]; n++);
3014 rmva = calloc(2 * n + 1, sizeof(uint32_t));
3016 debugx(1, DBG_ERR, "malloc failed");
3018 for (p = rmva, i = 0; i < n; i++, p += 2) {
3019 if (!vattrname2val(rmvattrs[i], p, p + 1))
3020 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
3028 adda = list_create();
3030 debugx(1, DBG_ERR, "malloc failed");
3031 for (i = 0; addattrs[i]; i++) {
3032 a = extractattr(addattrs[i]);
3034 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
3036 if (!list_push(adda, a))
3037 debugx(1, DBG_ERR, "malloc failed");
3043 moda = list_create();
3045 debugx(1, DBG_ERR, "malloc failed");
3046 for (i = 0; modattrs[i]; i++) {
3047 m = extractmodattr(modattrs[i]);
3049 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
3051 if (!list_push(moda, m))
3052 debugx(1, DBG_ERR, "malloc failed");
3057 if (rma || rmva || adda || moda) {
3058 rewrite = malloc(sizeof(struct rewrite));
3060 debugx(1, DBG_ERR, "malloc failed");
3061 rewrite->removeattrs = rma;
3062 rewrite->removevendorattrs = rmva;
3063 rewrite->addattrs = adda;
3064 rewrite->modattrs = moda;
3067 new = malloc(sizeof(struct rewriteconf));
3068 if (!new || !list_push(rewriteconfs, new))
3069 debugx(1, DBG_ERR, "malloc failed");
3071 memset(new, 0, sizeof(struct rewriteconf));
3072 new->name = stringcopy(value, 0);
3074 debugx(1, DBG_ERR, "malloc failed");
3076 new->rewrite = rewrite;
3077 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3080 void confclient_cb(struct gconffile **cf, char *block, char *opt, char *val) {
3081 char *type = NULL, *tls = NULL, *matchcertattr = NULL,
3082 *rewritein = NULL, *rewriteinalias = NULL, *rewriteout = NULL, *rewriteusername = NULL;
3083 struct clsrvconf *conf;
3085 debug(DBG_DBG, "confclient_cb called for %s", block);
3087 conf = malloc(sizeof(struct clsrvconf));
3088 if (!conf || !list_push(clconfs, conf))
3089 debugx(1, DBG_ERR, "malloc failed");
3090 memset(conf, 0, sizeof(struct clsrvconf));
3091 conf->certnamecheck = 1;
3093 getgenericconfig(cf, block,
3094 "type", CONF_STR, &type,
3095 "host", CONF_STR, &conf->host,
3096 "secret", CONF_STR, &conf->secret,
3097 "tls", CONF_STR, &tls,
3098 "matchcertificateattribute", CONF_STR, &matchcertattr,
3099 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3100 "rewrite", CONF_STR, &rewriteinalias,
3101 "rewriteIn", CONF_STR, &rewritein,
3102 "rewriteOut", CONF_STR, &rewriteout,
3103 "rewriteattribute", CONF_STR, &rewriteusername,
3107 conf->name = stringcopy(val, 0);
3109 conf->host = stringcopy(val, 0);
3111 if (type && !strcasecmp(type, "udp")) {
3114 } else if (type && !strcasecmp(type, "tls")) {
3115 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultclient", "default");
3117 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3118 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
3119 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3123 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
3128 free(matchcertattr);
3131 rewritein = rewriteinalias;
3133 free(rewriteinalias);
3134 conf->rewritein = rewritein ? getrewrite(rewritein, NULL) : getrewrite("defaultclient", "default");
3137 conf->rewriteout = getrewrite(rewriteout, NULL);
3141 if (rewriteusername) {
3142 conf->rewriteusername = extractmodattr(rewriteusername);
3143 if (!conf->rewriteusername)
3144 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3145 free(rewriteusername);
3148 if (!resolvepeer(conf, 0))
3149 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3151 if (!conf->secret) {
3152 if (conf->type == 'U')
3153 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
3154 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
3158 void confserver_cb(struct gconffile **cf, char *block, char *opt, char *val) {
3159 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *rewritein = NULL, *rewriteinalias = NULL, *rewriteout = NULL;
3160 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3161 struct clsrvconf *conf;
3163 debug(DBG_DBG, "confserver_cb called for %s", block);
3165 conf = malloc(sizeof(struct clsrvconf));
3166 if (!conf || !list_push(srvconfs, conf))
3167 debugx(1, DBG_ERR, "malloc failed");
3168 memset(conf, 0, sizeof(struct clsrvconf));
3169 conf->certnamecheck = 1;
3171 getgenericconfig(cf, block,
3172 "type", CONF_STR, &type,
3173 "host", CONF_STR, &conf->host,
3174 "port", CONF_STR, &conf->port,
3175 "secret", CONF_STR, &conf->secret,
3176 "tls", CONF_STR, &tls,
3177 "MatchCertificateAttribute", CONF_STR, &matchcertattr,
3178 "rewrite", CONF_STR, &rewriteinalias,
3179 "rewriteIn", CONF_STR, &rewritein,
3180 "rewriteOut", CONF_STR, &rewriteout,
3181 "StatusServer", CONF_BLN, &conf->statusserver,
3182 "RetryInterval", CONF_LINT, &retryinterval,
3183 "RetryCount", CONF_LINT, &retrycount,
3184 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3188 conf->name = stringcopy(val, 0);
3190 conf->host = stringcopy(val, 0);
3192 if (type && !strcasecmp(type, "udp")) {
3195 conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
3196 } else if (type && !strcasecmp(type, "tls")) {
3197 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultserver", "default");
3199 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3200 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
3201 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3203 conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
3206 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
3211 free(matchcertattr);
3213 if (retryinterval != LONG_MIN) {
3214 if (retryinterval < 1 || retryinterval > 60)
3215 debugx(1, DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-60", block, retryinterval);
3216 conf->retryinterval = (uint8_t)retryinterval;
3218 conf->retryinterval = REQUEST_RETRY_INTERVAL;
3220 if (retrycount != LONG_MIN) {
3221 if (retrycount < 0 || retrycount > 10)
3222 debugx(1, DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-10", block, retrycount);
3223 conf->retrycount = (uint8_t)retrycount;
3225 conf->retrycount = REQUEST_RETRY_COUNT;
3228 rewritein = rewriteinalias;
3230 free(rewriteinalias);
3231 conf->rewritein = rewritein ? getrewrite(rewritein, NULL) : getrewrite("defaultserver", "default");
3234 conf->rewriteout = getrewrite(rewriteout, NULL);
3238 if (!resolvepeer(conf, 0))
3239 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3241 if (!conf->secret) {
3242 if (conf->type == 'U')
3243 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
3244 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
3248 void confrealm_cb(struct gconffile **cf, char *block, char *opt, char *val) {
3249 char **servers = NULL, **accservers = NULL, *msg = NULL;
3250 uint8_t accresp = 0;
3252 debug(DBG_DBG, "confrealm_cb called for %s", block);
3254 getgenericconfig(cf, block,
3255 "server", CONF_MSTR, &servers,
3256 "accountingServer", CONF_MSTR, &accservers,
3257 "ReplyMessage", CONF_STR, &msg,
3258 "AccountingResponse", CONF_BLN, &accresp,
3262 addrealm(val, servers, accservers, msg, accresp);
3265 void conftls_cb(struct gconffile **cf, char *block, char *opt, char *val) {
3266 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
3267 uint8_t crlcheck = 0;
3269 debug(DBG_DBG, "conftls_cb called for %s", block);
3271 getgenericconfig(cf, block,
3272 "CACertificateFile", CONF_STR, &cacertfile,
3273 "CACertificatePath", CONF_STR, &cacertpath,
3274 "CertificateFile", CONF_STR, &certfile,
3275 "CertificateKeyFile", CONF_STR, &certkeyfile,
3276 "CertificateKeyPassword", CONF_STR, &certkeypwd,
3277 "CRLCheck", CONF_BLN, &crlcheck,
3281 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd, crlcheck);
3289 void confrewrite_cb(struct gconffile **cf, char *block, char *opt, char *val) {
3290 char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3292 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3294 getgenericconfig(cf, block,
3295 "removeAttribute", CONF_MSTR, &rmattrs,
3296 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3297 "addAttribute", CONF_MSTR, &addattrs,
3298 "modifyAttribute", CONF_MSTR, &modattrs,
3301 addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3304 void getmainconfig(const char *configfile) {
3305 long int loglevel = LONG_MIN;
3306 struct gconffile *cfs;
3308 cfs = openconfigfile(configfile);
3309 memset(&options, 0, sizeof(options));
3311 clconfs = list_create();
3313 debugx(1, DBG_ERR, "malloc failed");
3315 srvconfs = list_create();
3317 debugx(1, DBG_ERR, "malloc failed");
3319 realms = list_create();
3321 debugx(1, DBG_ERR, "malloc failed");
3323 tlsconfs = list_create();
3325 debugx(1, DBG_ERR, "malloc failed");
3327 rewriteconfs = list_create();
3329 debugx(1, DBG_ERR, "malloc failed");
3331 getgenericconfig(&cfs, NULL,
3332 "ListenUDP", CONF_STR, &options.listenudp,
3333 "ListenTCP", CONF_STR, &options.listentcp,
3334 "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
3335 "SourceUDP", CONF_STR, &options.sourceudp,
3336 "SourceTCP", CONF_STR, &options.sourcetcp,
3337 "LogLevel", CONF_LINT, &loglevel,
3338 "LogDestination", CONF_STR, &options.logdestination,
3339 "LoopPrevention", CONF_BLN, &options.loopprevention,
3340 "Client", CONF_CBK, confclient_cb,
3341 "Server", CONF_CBK, confserver_cb,
3342 "Realm", CONF_CBK, confrealm_cb,
3343 "TLS", CONF_CBK, conftls_cb,
3344 "Rewrite", CONF_CBK, confrewrite_cb,
3350 if (loglevel != LONG_MIN) {
3351 if (loglevel < 1 || loglevel > 4)
3352 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3353 options.loglevel = (uint8_t)loglevel;
3357 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3360 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3363 *configfile = optarg;
3366 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3367 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3368 *loglevel = *optarg - '0';
3377 debugx(0, DBG_ERR, "radsecproxy 1.1");
3382 if (!(argc - optind))
3386 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3390 int daemon(int a, int b) {
3398 for (i = 0; i < 3; i++) {
3400 open("/dev/null", O_RDWR);
3406 void *sighandler(void *arg) {
3411 sigemptyset(&sigset);
3412 sigaddset(&sigset, SIGPIPE);
3413 sigwait(&sigset, &sig);
3414 /* only get SIGPIPE right now, so could simplify below code */
3417 /* completely ignoring this */
3420 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3423 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3428 int main(int argc, char **argv) {
3429 pthread_t sigth, udpserverth, udpaccserverth, udpclient4rdth, udpclient6rdth;
3431 struct list_node *entry;
3432 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3433 char *configfile = NULL;
3435 debug_init("radsecproxy");
3436 debug_set_level(DEBUG_LEVEL);
3437 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3439 debug_set_level(loglevel);
3440 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3442 options.loglevel = loglevel;
3443 else if (options.loglevel)
3444 debug_set_level(options.loglevel);
3446 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3447 free(options.logdestination);
3449 if (!list_first(clconfs))
3450 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3451 if (!list_first(realms))
3452 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3455 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3457 if (!foreground && (daemon(0, 0) < 0))
3458 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3460 debug_timestamp_on();
3461 debug(DBG_INFO, "radsecproxy 1.1 starting");
3463 sigemptyset(&sigset);
3464 /* exit on all but SIGPIPE, ignore more? */
3465 sigaddset(&sigset, SIGPIPE);
3466 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3467 pthread_create(&sigth, NULL, sighandler, NULL);
3469 if (client_udp_count) {
3470 udp_server_replyq = newreplyq();
3471 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
3472 debugx(1, DBG_ERR, "pthread_create failed");
3473 if (options.listenaccudp)
3474 if (pthread_create(&udpaccserverth, NULL, udpaccserverrd, NULL))
3475 debugx(1, DBG_ERR, "pthread_create failed");
3478 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3479 addserver((struct clsrvconf *)entry->data);
3480 if (pthread_create(&((struct clsrvconf *)entry->data)->servers->clientth, NULL, clientwr,
3481 (void *)((struct clsrvconf *)entry->data)->servers))
3482 debugx(1, DBG_ERR, "pthread_create failed");
3484 /* srcudpres no longer needed, while srctcpres is needed later */
3486 freeaddrinfo(srcudpres);
3489 if (udp_client4_sock >= 0)
3490 if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
3491 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
3492 if (udp_client6_sock >= 0)
3493 if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
3494 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
3496 if (client_tls_count)
3497 return tlslistener();
3499 /* just hang around doing nothing, anything to do here? */