2 * Copyright (C) 2006, 2007 Stig Venaas <venaas@uninett.no>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
9 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
10 * rd is responsible for init and launching wr
11 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
12 * each tlsserverrd launches tlsserverwr
13 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
14 * for init and launching rd
16 * serverrd will receive a request, processes it and puts it in the requestq of
17 * the appropriate clientwr
18 * clientwr monitors its requestq and sends requests
19 * clientrd looks for responses, processes them and puts them in the replyq of
20 * the peer the request came from
21 * serverwr monitors its reply and sends replies
23 * In addition to the main thread, we have:
24 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
25 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
26 * For each TLS peer connecting to us there will be 2 more TLS threads
27 * This is only for connected peers
28 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
29 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
32 #include <sys/socket.h>
33 #include <netinet/in.h>
38 #include <sys/types.h>
39 #include <arpa/inet.h>
43 #include <openssl/ssl.h>
44 #include <openssl/rand.h>
45 #include <openssl/err.h>
46 #include <openssl/md5.h>
47 #include <openssl/hmac.h>
48 #include <openssl/x509v3.h>
51 #include "radsecproxy.h"
53 static struct options options;
54 struct list *clconfs, *srvconfs, *realms, *tlsconfs;
56 static int client_udp_count = 0;
57 static int client_tls_count = 0;
58 static int server_udp_count = 0;
59 static int server_tls_count = 0;
61 static struct clsrvconf *tcp_server_listen;
62 static struct clsrvconf *udp_server_listen;
63 static struct replyq *udp_server_replyq = NULL;
64 static int udp_server_sock = -1;
65 static pthread_mutex_t *ssl_locks;
66 static long *ssl_lock_count;
70 /* callbacks for making OpenSSL thread safe */
71 unsigned long ssl_thread_id() {
72 return (unsigned long)pthread_self();
75 void ssl_locking_callback(int mode, int type, const char *file, int line) {
76 if (mode & CRYPTO_LOCK) {
77 pthread_mutex_lock(&ssl_locks[type]);
78 ssl_lock_count[type]++;
80 pthread_mutex_unlock(&ssl_locks[type]);
83 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
84 int pwdlen = strlen(userdata);
85 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
87 memcpy(buf, userdata, pwdlen);
91 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
96 err_cert = X509_STORE_CTX_get_current_cert(ctx);
97 err = X509_STORE_CTX_get_error(ctx);
98 depth = X509_STORE_CTX_get_error_depth(ctx);
100 if (depth > MAX_CERT_DEPTH) {
102 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
103 X509_STORE_CTX_set_error(ctx, err);
107 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
108 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
111 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
112 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
113 debug(DBG_WARN, "\tIssuer=%s", buf);
115 case X509_V_ERR_CERT_NOT_YET_VALID:
116 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
117 debug(DBG_WARN, "\tCertificate not yet valid");
119 case X509_V_ERR_CERT_HAS_EXPIRED:
120 debug(DBG_WARN, "Certificate has expired");
122 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
123 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
128 printf("certificate verify returns %d\n", ok);
133 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
134 struct addrinfo hints, *addrinfo;
138 slash = conf->host ? strchr(conf->host, '/') : NULL;
142 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
146 if (*s < '0' || *s > '9') {
147 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
150 plen = atoi(slash + 1);
151 if (plen < 0 || plen > 128) {
152 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
157 memset(&hints, 0, sizeof(hints));
158 hints.ai_socktype = (conf->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
159 hints.ai_family = AF_UNSPEC;
160 hints.ai_flags = ai_flags;
162 hints.ai_flags |= AI_NUMERICHOST;
163 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
164 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host, conf->port);
170 switch (addrinfo->ai_family) {
173 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
174 freeaddrinfo(addrinfo);
181 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
182 freeaddrinfo(addrinfo);
185 conf->prefixlen = plen;
187 conf->prefixlen = 255;
190 freeaddrinfo(conf->addrinfo);
191 conf->addrinfo = addrinfo;
195 int connecttoserver(struct addrinfo *addrinfo) {
197 struct addrinfo *res;
200 for (res = addrinfo; res; res = res->ai_next) {
201 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
203 debug(DBG_WARN, "connecttoserver: socket failed");
206 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
208 debug(DBG_WARN, "connecttoserver: connect failed");
215 int bindtoaddr(struct addrinfo *addrinfo) {
217 struct addrinfo *res;
219 for (res = addrinfo; res; res = res->ai_next) {
220 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
222 debug(DBG_WARN, "bindtoaddr: socket failed");
225 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
226 if (!bind(s, res->ai_addr, res->ai_addrlen))
228 debug(DBG_WARN, "bindtoaddr: bind failed");
234 /* returns 1 if the len first bits are equal, else 0 */
235 int prefixmatch(void *a1, void *a2, uint8_t len) {
236 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
238 if (l && memcmp(a1, a2, l))
243 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
246 /* returns the config with matching address, or NULL */
247 /* if conf argument is not NULL, we only check that one */
248 struct clsrvconf *find_conf(char type, struct sockaddr *addr, struct list *confs, struct clsrvconf *conf) {
249 struct sockaddr_in6 *sa6 = NULL;
250 struct in_addr *a4 = NULL;
251 struct addrinfo *res;
252 struct list_node *entry;
254 if (addr->sa_family == AF_INET6) {
255 sa6 = (struct sockaddr_in6 *)addr;
256 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
257 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
261 a4 = &((struct sockaddr_in *)addr)->sin_addr;
264 if (conf->type == type) {
265 if (conf->prefixlen == 255) {
266 for (res = conf->addrinfo; res; res = res->ai_next)
267 if ((a4 && res->ai_family == AF_INET &&
268 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
269 (sa6 && res->ai_family == AF_INET6 &&
270 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
273 res = conf->addrinfo;
275 ((a4 && res->ai_family == AF_INET &&
276 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
277 (sa6 && res->ai_family == AF_INET6 &&
278 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
285 for (entry = list_first(confs); entry; entry = list_next(entry)) {
286 conf = (struct clsrvconf *)entry->data;
287 if (conf->type == type) {
288 if (conf->prefixlen == 255) {
289 for (res = conf->addrinfo; res; res = res->ai_next)
290 if ((a4 && res->ai_family == AF_INET &&
291 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
292 (sa6 && res->ai_family == AF_INET6 &&
293 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
296 res = conf->addrinfo;
298 ((a4 && res->ai_family == AF_INET &&
299 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
300 (sa6 && res->ai_family == AF_INET6 &&
301 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
309 struct replyq *newreplyq() {
310 struct replyq *replyq;
312 replyq = malloc(sizeof(struct replyq));
314 debugx(1, DBG_ERR, "malloc failed");
315 replyq->replies = list_create();
316 if (!replyq->replies)
317 debugx(1, DBG_ERR, "malloc failed");
318 pthread_mutex_init(&replyq->mutex, NULL);
319 pthread_cond_init(&replyq->cond, NULL);
323 struct client *addclient(struct clsrvconf *conf) {
324 struct client *new = malloc(sizeof(struct client));
327 debug(DBG_ERR, "malloc failed");
330 if (!conf->clients) {
331 conf->clients = list_create();
332 if (!conf->clients) {
333 debug(DBG_ERR, "malloc failed");
338 memset(new, 0, sizeof(struct client));
340 new->replyq = conf->type == 'T' ? newreplyq() : udp_server_replyq;
342 list_push(conf->clients, new);
346 void removeclient(struct client *client) {
347 if (!client || !client->conf->clients)
350 list_removedata(client->conf->clients, client);
354 void addserver(struct clsrvconf *conf) {
356 debugx(1, DBG_ERR, "currently works with just one server per conf");
358 conf->servers = malloc(sizeof(struct server));
360 debugx(1, DBG_ERR, "malloc failed");
361 memset(conf->servers, 0, sizeof(struct server));
362 conf->servers->conf = conf;
364 conf->servers->sock = -1;
365 pthread_mutex_init(&conf->servers->lock, NULL);
366 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
367 if (!conf->servers->requests)
368 debugx(1, DBG_ERR, "malloc failed");
369 conf->servers->newrq = 0;
370 pthread_mutex_init(&conf->servers->newrq_mutex, NULL);
371 pthread_cond_init(&conf->servers->newrq_cond, NULL);
374 /* exactly one of client and server must be non-NULL */
375 /* should probably take peer list (client(s) or server(s)) as argument instead */
376 /* if *peer == NULL we return who we received from, else require it to be from peer */
377 /* return from in sa if not NULL */
378 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
380 unsigned char buf[65536], *rad;
381 struct sockaddr_storage from;
382 socklen_t fromlen = sizeof(from);
384 struct list_node *node;
387 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
389 debug(DBG_WARN, "radudpget: recv failed");
392 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
395 debug(DBG_WARN, "radudpget: packet too small");
401 debug(DBG_WARN, "radudpget: length too small");
406 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
410 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
414 p = find_conf('U', (struct sockaddr *)&from, NULL, (*client)->conf);
416 p = find_conf('U', (struct sockaddr *)&from, clconfs, NULL);
419 p = find_conf('U', (struct sockaddr *)&from, NULL, (*server)->conf);
421 p = find_conf('U', (struct sockaddr *)&from, srvconfs, NULL);
424 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer, ignoring");
430 debug(DBG_ERR, "radudpget: malloc failed");
434 if (client && !*client) {
435 node = list_first(p->clients);
436 *client = node ? (struct client *)node->data : addclient(p);
441 } else if (server && !*server)
442 *server = p->servers;
446 memcpy(rad, buf, len);
452 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
453 int loc, i, l, n, r = 0;
456 STACK_OF(GENERAL_NAME) *alt;
459 debug(DBG_DBG, "subjectaltnameaddr");
461 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
465 ex = X509_get_ext(cert, loc);
466 alt = X509V3_EXT_d2i(ex);
470 n = sk_GENERAL_NAME_num(alt);
471 for (i = 0; i < n; i++) {
472 gn = sk_GENERAL_NAME_value(alt, i);
473 if (gn->type != GEN_IPADD)
476 v = (char *)ASN1_STRING_data(gn->d.ia5);
477 l = ASN1_STRING_length(gn->d.ia5);
478 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
479 && !memcmp(v, &addr, l)) {
484 GENERAL_NAMES_free(alt);
488 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
489 int loc, i, l, n, r = 0;
492 STACK_OF(GENERAL_NAME) *alt;
495 debug(DBG_DBG, "subjectaltnameregexp");
497 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
501 ex = X509_get_ext(cert, loc);
502 alt = X509V3_EXT_d2i(ex);
506 n = sk_GENERAL_NAME_num(alt);
507 for (i = 0; i < n; i++) {
508 gn = sk_GENERAL_NAME_value(alt, i);
509 if (gn->type != type)
512 v = (char *)ASN1_STRING_data(gn->d.ia5);
513 l = ASN1_STRING_length(gn->d.ia5);
517 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
520 if (memcmp(v, exact, l))
523 s = stringcopy((char *)v, l);
525 debug(DBG_ERR, "malloc failed");
528 if (regexec(regex, s, 0, NULL, 0)) {
537 GENERAL_NAMES_free(alt);
541 int tlsverifycert(SSL *ssl, struct clsrvconf *conf) {
548 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
550 struct in6_addr addr;
552 if (SSL_get_verify_result(ssl) != X509_V_OK) {
553 debug(DBG_ERR, "tlsverifycert: basic validation failed");
554 while ((error = ERR_get_error()))
555 debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
559 cert = SSL_get_peer_certificate(ssl);
561 debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
565 if (inet_pton(AF_INET, conf->host, &addr))
567 else if (inet_pton(AF_INET6, conf->host, &addr))
570 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
574 debug(DBG_DBG, "tlsverifycert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
577 debug(DBG_DBG, "tlsverifycert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
579 nm = X509_get_subject_name(cert);
582 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
585 e = X509_NAME_get_entry(nm, loc);
586 s = X509_NAME_ENTRY_get_data(e);
587 v = (char *) ASN1_STRING_data(s);
588 l = ASN1_STRING_length(s);
592 printfchars(NULL, "cn", NULL, v, l);
594 if (l == strlen(conf->host) && !strncasecmp(conf->host, v, l)) {
596 debug(DBG_DBG, "tlsverifycert: Found cn matching host %s", conf->host);
602 debug(DBG_ERR, "tlsverifycert: cn not matching host %s", conf->host);
606 if (conf->certuriregex) {
607 r = subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex);
609 debug(DBG_DBG, "tlsverifycert: subjectaltname URI not matching regex");
613 debug(DBG_DBG, "tlsverifycert: subjectaltname URI matching regex");
619 void tlsconnect(struct server *server, struct timeval *when, char *text) {
623 debug(DBG_DBG, "tlsconnect called from %s", text);
624 pthread_mutex_lock(&server->lock);
625 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
626 /* already reconnected, nothing to do */
627 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
628 pthread_mutex_unlock(&server->lock);
632 debug(DBG_DBG, "tlsconnect %s", text);
635 gettimeofday(&now, NULL);
636 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
637 if (server->connectionok) {
638 server->connectionok = 0;
640 } else if (elapsed < 5)
642 else if (elapsed < 300) {
643 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
645 } else if (elapsed < 100000) {
646 debug(DBG_INFO, "tlsconnect: sleeping %ds", 600);
649 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
650 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
651 if (server->sock >= 0)
653 if ((server->sock = connecttoserver(server->conf->addrinfo)) < 0) {
654 debug(DBG_ERR, "tlsconnect: connecttoserver failed");
658 SSL_free(server->ssl);
659 server->ssl = SSL_new(server->conf->ssl_ctx);
660 SSL_set_fd(server->ssl, server->sock);
661 if (SSL_connect(server->ssl) > 0 && tlsverifycert(server->ssl, server->conf))
664 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
665 gettimeofday(&server->lastconnecttry, NULL);
666 pthread_mutex_unlock(&server->lock);
669 unsigned char *radtlsget(SSL *ssl) {
671 unsigned char buf[4], *rad;
674 for (total = 0; total < 4; total += cnt) {
675 cnt = SSL_read(ssl, buf + total, 4 - total);
677 debug(DBG_ERR, "radtlsget: connection lost");
678 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
679 /* remote end sent close_notify, send one back */
689 debug(DBG_ERR, "radtlsget: malloc failed");
694 for (; total < len; total += cnt) {
695 cnt = SSL_read(ssl, rad + total, len - total);
697 debug(DBG_ERR, "radtlsget: connection lost");
698 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
699 /* remote end sent close_notify, send one back */
711 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
714 debug(DBG_DBG, "radtlsget: got %d bytes", total);
718 int clientradput(struct server *server, unsigned char *rad) {
722 struct timeval lastconnecttry;
725 if (server->conf->type == 'U') {
726 if (send(server->sock, rad, len, 0) >= 0) {
727 debug(DBG_DBG, "clienradput: sent UDP of length %d to %s port %s", len, server->conf->host, server->conf->port);
730 debug(DBG_WARN, "clientradput: send failed");
734 lastconnecttry = server->lastconnecttry;
735 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
736 while ((error = ERR_get_error()))
737 debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
738 tlsconnect(server, &lastconnecttry, "clientradput");
739 lastconnecttry = server->lastconnecttry;
742 server->connectionok = 1;
743 debug(DBG_DBG, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s",
744 cnt, len, server->conf->host);
748 int radsign(unsigned char *rad, unsigned char *sec) {
749 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
750 static unsigned char first = 1;
751 static EVP_MD_CTX mdctx;
755 pthread_mutex_lock(&lock);
757 EVP_MD_CTX_init(&mdctx);
761 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
762 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
763 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
764 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
766 pthread_mutex_unlock(&lock);
770 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
771 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
772 static unsigned char first = 1;
773 static EVP_MD_CTX mdctx;
774 unsigned char hash[EVP_MAX_MD_SIZE];
778 pthread_mutex_lock(&lock);
780 EVP_MD_CTX_init(&mdctx);
786 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
787 EVP_DigestUpdate(&mdctx, rad, 4) &&
788 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
789 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
790 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
791 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
793 !memcmp(hash, rad + 4, 16));
794 pthread_mutex_unlock(&lock);
798 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
799 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
800 static unsigned char first = 1;
801 static HMAC_CTX hmacctx;
803 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
805 pthread_mutex_lock(&lock);
807 HMAC_CTX_init(&hmacctx);
811 memcpy(auth, authattr, 16);
812 memset(authattr, 0, 16);
814 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
815 HMAC_Update(&hmacctx, rad, RADLEN(rad));
816 HMAC_Final(&hmacctx, hash, &md_len);
817 memcpy(authattr, auth, 16);
819 debug(DBG_WARN, "message auth computation failed");
820 pthread_mutex_unlock(&lock);
824 if (memcmp(auth, hash, 16)) {
825 debug(DBG_WARN, "message authenticator, wrong value");
826 pthread_mutex_unlock(&lock);
830 pthread_mutex_unlock(&lock);
834 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
835 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
836 static unsigned char first = 1;
837 static HMAC_CTX hmacctx;
843 pthread_mutex_lock(&lock);
845 HMAC_CTX_init(&hmacctx);
849 memset(authattrval, 0, 16);
851 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
852 HMAC_Update(&hmacctx, rad, RADLEN(rad));
853 HMAC_Final(&hmacctx, authattrval, &md_len);
855 debug(DBG_WARN, "message auth computation failed");
856 pthread_mutex_unlock(&lock);
860 pthread_mutex_unlock(&lock);
864 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
866 if (ATTRTYPE(attrs) == type)
868 length -= ATTRLEN(attrs);
869 attrs += ATTRLEN(attrs);
874 void sendrq(struct server *to, struct request *rq) {
878 pthread_mutex_lock(&to->newrq_mutex);
879 /* might simplify if only try nextid, might be ok */
880 for (i = to->nextid; i < MAX_REQUESTS; i++)
881 if (!to->requests[i].buf)
883 if (i == MAX_REQUESTS) {
884 for (i = 0; i < to->nextid; i++)
885 if (!to->requests[i].buf)
887 if (i == to->nextid) {
888 debug(DBG_WARN, "No room in queue, dropping request");
890 pthread_mutex_unlock(&to->newrq_mutex);
895 rq->buf[1] = (char)i;
897 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
898 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
900 pthread_mutex_unlock(&to->newrq_mutex);
904 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
905 to->requests[i] = *rq;
910 debug(DBG_DBG, "signalling client writer");
911 pthread_cond_signal(&to->newrq_cond);
913 pthread_mutex_unlock(&to->newrq_mutex);
916 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
920 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
922 debug(DBG_WARN, "sendreply: failed to sign message");
926 reply = malloc(sizeof(struct reply));
929 debug(DBG_ERR, "sendreply: malloc failed");
932 memset(reply, 0, sizeof(struct reply));
937 pthread_mutex_lock(&to->replyq->mutex);
939 first = list_first(to->replyq->replies) == NULL;
941 if (!list_push(to->replyq->replies, reply)) {
942 pthread_mutex_unlock(&to->replyq->mutex);
945 debug(DBG_ERR, "sendreply: malloc failed");
950 debug(DBG_DBG, "signalling server writer");
951 pthread_cond_signal(&to->replyq->cond);
953 pthread_mutex_unlock(&to->replyq->mutex);
956 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
957 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
958 static unsigned char first = 1;
959 static EVP_MD_CTX mdctx;
960 unsigned char hash[EVP_MAX_MD_SIZE], *input;
962 uint8_t i, offset = 0, out[128];
964 pthread_mutex_lock(&lock);
966 EVP_MD_CTX_init(&mdctx);
972 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
973 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
974 !EVP_DigestUpdate(&mdctx, input, 16) ||
975 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
977 pthread_mutex_unlock(&lock);
980 for (i = 0; i < 16; i++)
981 out[offset + i] = hash[i] ^ in[offset + i];
982 input = out + offset - 16;
987 memcpy(in, out, len);
988 pthread_mutex_unlock(&lock);
992 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
993 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
994 static unsigned char first = 1;
995 static EVP_MD_CTX mdctx;
996 unsigned char hash[EVP_MAX_MD_SIZE], *input;
998 uint8_t i, offset = 0, out[128];
1000 pthread_mutex_lock(&lock);
1002 EVP_MD_CTX_init(&mdctx);
1008 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1009 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1010 !EVP_DigestUpdate(&mdctx, input, 16) ||
1011 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1013 pthread_mutex_unlock(&lock);
1016 for (i = 0; i < 16; i++)
1017 out[offset + i] = hash[i] ^ in[offset + i];
1018 input = in + offset;
1023 memcpy(in, out, len);
1024 pthread_mutex_unlock(&lock);
1028 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1029 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1030 static unsigned char first = 1;
1031 static EVP_MD_CTX mdctx;
1032 unsigned char hash[EVP_MAX_MD_SIZE];
1033 unsigned int md_len;
1036 pthread_mutex_lock(&lock);
1038 EVP_MD_CTX_init(&mdctx);
1043 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1044 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1045 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1048 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1049 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1050 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1051 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1052 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1053 pthread_mutex_unlock(&lock);
1058 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1061 for (i = 0; i < 16; i++)
1064 for (offset = 16; offset < len; offset += 16) {
1066 printf("text + offset - 16 c(%d): ", offset / 16);
1067 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1069 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1070 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1071 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1072 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1074 pthread_mutex_unlock(&lock);
1078 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1081 for (i = 0; i < 16; i++)
1082 text[offset + i] ^= hash[i];
1086 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1089 pthread_mutex_unlock(&lock);
1093 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1094 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1095 static unsigned char first = 1;
1096 static EVP_MD_CTX mdctx;
1097 unsigned char hash[EVP_MAX_MD_SIZE];
1098 unsigned int md_len;
1102 pthread_mutex_lock(&lock);
1104 EVP_MD_CTX_init(&mdctx);
1109 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1110 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1111 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1114 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1115 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1116 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1117 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1118 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1119 pthread_mutex_unlock(&lock);
1124 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1127 for (i = 0; i < 16; i++)
1128 plain[i] = text[i] ^ hash[i];
1130 for (offset = 16; offset < len; offset += 16) {
1132 printf("text + offset - 16 c(%d): ", offset / 16);
1133 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1135 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1136 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1137 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1138 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1140 pthread_mutex_unlock(&lock);
1144 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1147 for (i = 0; i < 16; i++)
1148 plain[offset + i] = text[offset + i] ^ hash[i];
1151 memcpy(text, plain, len);
1153 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1156 pthread_mutex_unlock(&lock);
1160 struct realm *id2realm(char *id, uint8_t len) {
1161 struct list_node *entry;
1162 struct realm *realm;
1164 for (entry = list_first(realms); entry; entry = list_next(entry)) {
1165 realm = (struct realm *)entry->data;
1166 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1167 debug(DBG_DBG, "found matching realm: %s", realm->name);
1174 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
1177 pthread_mutex_lock(&to->newrq_mutex);
1178 for (i = 0; i < MAX_REQUESTS; i++)
1179 if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
1181 pthread_mutex_unlock(&to->newrq_mutex);
1183 return i < MAX_REQUESTS;
1186 int attrvalidate(unsigned char *attrs, int length) {
1187 while (length > 1) {
1188 if (ATTRLEN(attrs) < 2) {
1189 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1192 length -= ATTRLEN(attrs);
1194 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1197 attrs += ATTRLEN(attrs);
1200 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1204 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1205 if (len < 16 || len > 128 || len % 16) {
1206 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1210 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1211 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1215 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1217 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1218 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1224 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1227 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1228 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1231 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1232 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1238 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1239 char *oldsecret, char *newsecret) {
1240 unsigned char *attr;
1242 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1243 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1244 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1250 void respondstatusserver(struct request *rq) {
1251 unsigned char *resp;
1255 debug(DBG_ERR, "respondstatusserver: malloc failed");
1258 memcpy(resp, rq->buf, 20);
1259 resp[0] = RAD_Access_Accept;
1262 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1263 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1266 void respondreject(struct request *rq, char *message) {
1267 unsigned char *resp;
1271 len += 2 + strlen(message);
1275 debug(DBG_ERR, "respondreject: malloc failed");
1278 memcpy(resp, rq->buf, 20);
1279 resp[0] = RAD_Access_Reject;
1280 *(uint16_t *)(resp + 2) = htons(len);
1282 resp[20] = RAD_Attr_Reply_Message;
1283 resp[21] = len - 20;
1284 memcpy(resp + 22, message, len - 22);
1286 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1289 struct server *realm2server(struct realm *realm) {
1290 struct list_node *entry;
1291 struct server *server, *best = NULL;
1293 for (entry = list_first(realm->srvconfs); entry; entry = list_next(entry)) {
1294 server = ((struct clsrvconf *)entry->data)->servers;
1295 if (!server->connectionok)
1297 if (!server->loststatsrv)
1303 if (server->loststatsrv < best->loststatsrv)
1309 void radsrv(struct request *rq) {
1310 uint8_t code, id, *auth, *attrs, *attr;
1312 struct server *to = NULL;
1314 unsigned char *buf, newauth[16];
1315 struct realm *realm = NULL;
1318 code = *(uint8_t *)buf;
1319 id = *(uint8_t *)(buf + 1);
1321 auth = (uint8_t *)(buf + 4);
1323 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1325 if (code != RAD_Access_Request && code != RAD_Status_Server) {
1326 debug(DBG_INFO, "radsrv: server currently accepts only access-requests and status-server, ignoring");
1334 if (!attrvalidate(attrs, len)) {
1335 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1340 if (code == RAD_Access_Request) {
1341 attr = attrget(attrs, len, RAD_Attr_User_Name);
1343 debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1347 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1348 username[ATTRVALLEN(attr)] = '\0';
1349 debug(DBG_DBG, "Access Request with username: %s", username);
1351 realm = id2realm(username, strlen(username));
1353 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1358 to = realm2server(realm);
1359 if (to && rqinqueue(to, rq->from, id)) {
1360 debug(DBG_INFO, "radsrv: already got request from host %s with id %d, ignoring", rq->from->conf->host, id);
1366 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1367 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(buf, ATTRVAL(attr), rq->from->conf->secret))) {
1368 debug(DBG_WARN, "radsrv: message authentication failed");
1373 if (code == RAD_Status_Server) {
1374 respondstatusserver(rq);
1379 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, username);
1380 respondreject(rq, realm->message);
1384 if (!RAND_bytes(newauth, 16)) {
1385 debug(DBG_WARN, "radsrv: failed to generate random auth");
1391 printfchars(NULL, "auth", "%02x ", auth, 16);
1394 attr = attrget(attrs, len, RAD_Attr_User_Password);
1396 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1397 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1403 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1405 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1406 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1413 memcpy(rq->origauth, auth, 16);
1414 memcpy(auth, newauth, 16);
1418 void *clientrd(void *arg) {
1419 struct server *server = (struct server *)arg;
1420 struct client *from;
1422 unsigned char *buf, *messageauth, *subattrs, *attrs, *attr;
1423 struct sockaddr_storage fromsa;
1424 struct timeval lastconnecttry;
1428 lastconnecttry = server->lastconnecttry;
1429 buf = (server->conf->type == 'U' ? radudpget(server->sock, NULL, &server, NULL) : radtlsget(server->ssl));
1430 if (!buf && server->conf->type == 'T') {
1431 tlsconnect(server, &lastconnecttry, "clientrd");
1435 server->connectionok = 1;
1436 server->loststatsrv = 0;
1438 i = buf[1]; /* i is the id */
1441 case RAD_Access_Accept:
1442 debug(DBG_DBG, "got Access Accept with id %d", i);
1444 case RAD_Access_Reject:
1445 debug(DBG_DBG, "got Access Reject with id %d", i);
1447 case RAD_Access_Challenge:
1448 debug(DBG_DBG, "got Access Challenge with id %d", i);
1452 debug(DBG_INFO, "clientrd: discarding, only accept access accept, access reject and access challenge messages");
1456 pthread_mutex_lock(&server->newrq_mutex);
1457 if (!server->requests[i].buf || !server->requests[i].tries) {
1458 pthread_mutex_unlock(&server->newrq_mutex);
1460 debug(DBG_INFO, "clientrd: no matching request sent with this id, ignoring");
1464 if (server->requests[i].received) {
1465 pthread_mutex_unlock(&server->newrq_mutex);
1467 debug(DBG_INFO, "clientrd: already received, ignoring");
1471 if (!validauth(buf, server->requests[i].buf + 4, (unsigned char *)server->conf->secret)) {
1472 pthread_mutex_unlock(&server->newrq_mutex);
1474 debug(DBG_WARN, "clientrd: invalid auth, ignoring");
1478 from = server->requests[i].from;
1479 len = RADLEN(buf) - 20;
1482 if (!attrvalidate(attrs, len)) {
1483 pthread_mutex_unlock(&server->newrq_mutex);
1485 debug(DBG_WARN, "clientrd: attribute validation failed, ignoring packet");
1489 /* Message Authenticator */
1490 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1492 if (ATTRVALLEN(messageauth) != 16) {
1493 pthread_mutex_unlock(&server->newrq_mutex);
1495 debug(DBG_WARN, "clientrd: illegal message auth attribute length, ignoring packet");
1498 memcpy(tmp, buf + 4, 16);
1499 memcpy(buf + 4, server->requests[i].buf + 4, 16);
1500 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
1501 pthread_mutex_unlock(&server->newrq_mutex);
1503 debug(DBG_WARN, "clientrd: message authentication failed");
1506 memcpy(buf + 4, tmp, 16);
1507 debug(DBG_DBG, "clientrd: message auth ok");
1510 if (*server->requests[i].buf == RAD_Status_Server) {
1511 server->requests[i].received = 1;
1512 pthread_mutex_unlock(&server->newrq_mutex);
1514 debug(DBG_INFO, "clientrd: got status server response from %s", server->conf->host);
1519 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1520 if (ATTRVALLEN(attr) <= 4)
1523 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
1526 sublen = ATTRVALLEN(attr) - 4;
1527 subattrs = ATTRVAL(attr) + 4;
1528 if (!attrvalidate(subattrs, sublen) ||
1529 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1530 server->requests + i, server->conf->secret, from->conf->secret) ||
1531 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1532 server->requests + i, server->conf->secret, from->conf->secret))
1536 pthread_mutex_unlock(&server->newrq_mutex);
1538 debug(DBG_WARN, "clientrd: MS attribute handling failed, ignoring packet");
1542 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject) {
1543 attr = attrget(server->requests[i].buf + 20, RADLEN(server->requests[i].buf) - 20, RAD_Attr_User_Name);
1544 /* we know the attribute exists */
1545 memcpy(tmp, ATTRVAL(attr), ATTRVALLEN(attr));
1546 tmp[ATTRVALLEN(attr)] = '\0';
1548 case RAD_Access_Accept:
1549 debug(DBG_INFO, "Access Accept for %s from %s", tmp, server->conf->host);
1551 case RAD_Access_Reject:
1552 debug(DBG_INFO, "Access Reject for %s from %s", tmp, server->conf->host);
1557 /* once we set received = 1, requests[i] may be reused */
1558 buf[1] = (char)server->requests[i].origid;
1559 memcpy(buf + 4, server->requests[i].origauth, 16);
1561 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1565 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
1566 pthread_mutex_unlock(&server->newrq_mutex);
1570 debug(DBG_DBG, "clientrd: computed messageauthattr");
1573 if (from->conf->type == 'U')
1574 fromsa = server->requests[i].fromsa;
1575 server->requests[i].received = 1;
1576 pthread_mutex_unlock(&server->newrq_mutex);
1578 debug(DBG_DBG, "clientrd: giving packet back to where it came from");
1579 sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
1583 void *clientwr(void *arg) {
1584 struct server *server = (struct server *)arg;
1586 pthread_t clientrdth;
1589 struct timeval now, lastsend;
1590 struct timespec timeout;
1591 struct request statsrvrq;
1592 unsigned char statsrvbuf[38];
1594 memset(&timeout, 0, sizeof(struct timespec));
1596 if (server->conf->statusserver) {
1597 memset(&statsrvrq, 0, sizeof(struct request));
1598 memset(statsrvbuf, 0, sizeof(statsrvbuf));
1599 statsrvbuf[0] = RAD_Status_Server;
1601 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
1602 statsrvbuf[21] = 18;
1603 gettimeofday(&lastsend, NULL);
1606 if (server->conf->type == 'U') {
1607 if ((server->sock = connecttoserver(server->conf->addrinfo)) < 0)
1608 debugx(1, DBG_ERR, "clientwr: connecttoserver failed");
1609 server->connectionok = 1;
1611 tlsconnect(server, NULL, "new client");
1613 if (pthread_create(&clientrdth, NULL, clientrd, (void *)server))
1614 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
1617 pthread_mutex_lock(&server->newrq_mutex);
1618 if (!server->newrq) {
1619 gettimeofday(&now, NULL);
1620 if (server->conf->statusserver) {
1621 /* random 0-7 seconds */
1622 RAND_bytes(&rnd, 1);
1624 if (!timeout.tv_sec || timeout.tv_sec - now.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
1625 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
1627 if (timeout.tv_sec) {
1628 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1629 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1632 debug(DBG_DBG, "clientwr: waiting for new request");
1633 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1636 if (server->newrq) {
1637 debug(DBG_DBG, "clientwr: got new request");
1640 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1641 pthread_mutex_unlock(&server->newrq_mutex);
1643 for (i = 0; i < MAX_REQUESTS; i++) {
1644 pthread_mutex_lock(&server->newrq_mutex);
1645 while (i < MAX_REQUESTS && !server->requests[i].buf)
1647 if (i == MAX_REQUESTS) {
1648 pthread_mutex_unlock(&server->newrq_mutex);
1651 rq = server->requests + i;
1654 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
1656 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
1658 /* setting this to NULL means that it can be reused */
1661 pthread_mutex_unlock(&server->newrq_mutex);
1665 gettimeofday(&now, NULL);
1666 if (now.tv_sec < rq->expiry.tv_sec) {
1667 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1668 timeout.tv_sec = rq->expiry.tv_sec;
1669 pthread_mutex_unlock(&server->newrq_mutex);
1673 if (rq->tries == (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
1674 ? 1 : REQUEST_RETRIES)) {
1675 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1676 if (*rq->buf == RAD_Status_Server) {
1677 debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->conf->host);
1678 if (server->loststatsrv < 255)
1679 server->loststatsrv++;
1682 /* setting this to NULL means that it can be reused */
1684 pthread_mutex_unlock(&server->newrq_mutex);
1687 pthread_mutex_unlock(&server->newrq_mutex);
1689 rq->expiry.tv_sec = now.tv_sec +
1690 (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
1691 ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
1692 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1693 timeout.tv_sec = rq->expiry.tv_sec;
1695 clientradput(server, server->requests[i].buf);
1696 gettimeofday(&lastsend, NULL);
1698 if (server->conf->statusserver) {
1699 gettimeofday(&now, NULL);
1700 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
1701 if (!RAND_bytes(statsrvbuf + 4, 16)) {
1702 debug(DBG_WARN, "clientwr: failed to generate random auth");
1705 statsrvrq.buf = malloc(sizeof(statsrvbuf));
1706 if (!statsrvrq.buf) {
1707 debug(DBG_ERR, "clientwr: malloc failed");
1710 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
1711 debug(DBG_DBG, "clientwr: sending status server to %s", server->conf->host);
1712 lastsend.tv_sec = now.tv_sec;
1713 sendrq(server, &statsrvrq);
1719 void *udpserverwr(void *arg) {
1720 struct replyq *replyq = udp_server_replyq;
1721 struct reply *reply;
1724 pthread_mutex_lock(&replyq->mutex);
1725 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
1726 debug(DBG_DBG, "udp server writer, waiting for signal");
1727 pthread_cond_wait(&replyq->cond, &replyq->mutex);
1728 debug(DBG_DBG, "udp server writer, got signal");
1730 pthread_mutex_unlock(&replyq->mutex);
1732 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
1733 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
1734 debug(DBG_WARN, "sendudp: send failed");
1740 void *udpserverrd(void *arg) {
1742 pthread_t udpserverwrth;
1744 if ((udp_server_sock = bindtoaddr(udp_server_listen->addrinfo)) < 0)
1745 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
1747 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
1748 udp_server_listen->host ? udp_server_listen->host : "*", udp_server_listen->port);
1750 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
1751 debugx(1, DBG_ERR, "pthread_create failed");
1754 memset(&rq, 0, sizeof(struct request));
1755 rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
1760 void *tlsserverwr(void *arg) {
1762 unsigned long error;
1763 struct client *client = (struct client *)arg;
1764 struct replyq *replyq;
1765 struct reply *reply;
1767 debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
1768 replyq = client->replyq;
1770 pthread_mutex_lock(&replyq->mutex);
1771 while (!list_first(replyq->replies)) {
1773 debug(DBG_DBG, "tls server writer, waiting for signal");
1774 pthread_cond_wait(&replyq->cond, &replyq->mutex);
1775 debug(DBG_DBG, "tls server writer, got signal");
1778 /* ssl might have changed while waiting */
1779 pthread_mutex_unlock(&replyq->mutex);
1780 debug(DBG_DBG, "tlsserverwr: exiting as requested");
1784 reply = (struct reply *)list_shift(replyq->replies);
1785 pthread_mutex_unlock(&replyq->mutex);
1786 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
1788 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
1789 cnt, RADLEN(reply->buf));
1791 while ((error = ERR_get_error()))
1792 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
1798 void *tlsserverrd(void *arg) {
1800 unsigned long error;
1802 struct client *client = (struct client *)arg;
1803 pthread_t tlsserverwrth;
1806 debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
1809 if (SSL_accept(ssl) <= 0) {
1810 while ((error = ERR_get_error()))
1811 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
1812 debug(DBG_ERR, "SSL_accept failed");
1815 if (tlsverifycert(client->ssl, client->conf)) {
1816 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
1817 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
1821 memset(&rq, 0, sizeof(struct request));
1822 rq.buf = radtlsget(client->ssl);
1825 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
1829 debug(DBG_ERR, "tlsserverrd: connection lost");
1830 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
1832 pthread_mutex_lock(&client->replyq->mutex);
1833 pthread_cond_signal(&client->replyq->cond);
1834 pthread_mutex_unlock(&client->replyq->mutex);
1835 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
1836 pthread_join(tlsserverwrth, NULL);
1840 s = SSL_get_fd(ssl);
1842 shutdown(s, SHUT_RDWR);
1844 debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->conf->host);
1845 removeclient(client);
1850 pthread_t tlsserverth;
1852 struct sockaddr_storage from;
1853 size_t fromlen = sizeof(from);
1854 struct clsrvconf *conf;
1855 struct client *client;
1857 if ((s = bindtoaddr(tcp_server_listen->addrinfo)) < 0)
1858 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
1861 debug(DBG_WARN, "listening for incoming TCP on %s:%s",
1862 tcp_server_listen->host ? tcp_server_listen->host : "*", tcp_server_listen->port);
1865 snew = accept(s, (struct sockaddr *)&from, &fromlen);
1867 debug(DBG_WARN, "accept failed");
1870 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
1872 conf = find_conf('T', (struct sockaddr *)&from, clconfs, NULL);
1874 debug(DBG_WARN, "ignoring request, not a known TLS client");
1875 shutdown(snew, SHUT_RDWR);
1880 client = addclient(conf);
1883 debug(DBG_WARN, "Failed to create new client instance");
1884 shutdown(snew, SHUT_RDWR);
1888 client->ssl = SSL_new(client->conf->ssl_ctx);
1889 SSL_set_fd(client->ssl, snew);
1890 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
1891 debug(DBG_ERR, "tlslistener: pthread_create failed");
1892 SSL_free(client->ssl);
1893 removeclient(client);
1894 shutdown(snew, SHUT_RDWR);
1898 pthread_detach(tlsserverth);
1903 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
1907 unsigned long error;
1909 if (!certfile || !certkeyfile)
1910 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
1912 if (!cacertfile && !cacertpath)
1913 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
1916 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
1917 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
1918 for (i = 0; i < CRYPTO_num_locks(); i++) {
1919 ssl_lock_count[i] = 0;
1920 pthread_mutex_init(&ssl_locks[i], NULL);
1922 CRYPTO_set_id_callback(ssl_thread_id);
1923 CRYPTO_set_locking_callback(ssl_locking_callback);
1925 SSL_load_error_strings();
1928 while (!RAND_status()) {
1929 time_t t = time(NULL);
1930 pid_t pid = getpid();
1931 RAND_seed((unsigned char *)&t, sizeof(time_t));
1932 RAND_seed((unsigned char *)&pid, sizeof(pid));
1935 ctx = SSL_CTX_new(TLSv1_method());
1937 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
1938 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
1940 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
1941 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
1942 !SSL_CTX_check_private_key(ctx) ||
1943 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
1944 while ((error = ERR_get_error()))
1945 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
1946 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
1949 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
1950 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
1952 new = malloc(sizeof(struct tls));
1953 if (!new || !list_push(tlsconfs, new))
1954 debugx(1, DBG_ERR, "malloc failed");
1956 memset(new, 0, sizeof(struct tls));
1957 new->name = stringcopy(value, 0);
1959 debugx(1, DBG_ERR, "malloc failed");
1962 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
1966 struct list_node *entry;
1969 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
1970 t = (struct tls *)entry->data;
1974 SSL_CTX_free(t->ctx);
1976 list_destroy(tlsconfs);
1980 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
1981 struct list_node *entry;
1982 struct tls *t, *t1 = NULL, *t2 = NULL;
1984 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
1985 t = (struct tls *)entry->data;
1986 if (!strcasecmp(t->name, alt1)) {
1990 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2001 void addrealm(char *value, char **servers, char *message) {
2003 struct realm *realm;
2004 char *s, *regex = NULL;
2005 struct list_node *entry;
2006 struct clsrvconf *conf;
2008 if (*value == '/') {
2009 /* regexp, remove optional trailing / if present */
2010 if (value[strlen(value) - 1] == '/')
2011 value[strlen(value) - 1] = '\0';
2013 /* not a regexp, let us make it one */
2014 if (*value == '*' && !value[1])
2015 regex = stringcopy(".*", 0);
2017 for (n = 0, s = value; *s;)
2020 regex = malloc(strlen(value) + n + 3);
2023 for (n = 1, s = value; *s; s++) {
2033 debugx(1, DBG_ERR, "malloc failed");
2034 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2037 realm = malloc(sizeof(struct realm));
2039 debugx(1, DBG_ERR, "malloc failed");
2041 memset(realm, 0, sizeof(struct realm));
2042 realm->name = stringcopy(value, 0);
2044 debugx(1, DBG_ERR, "malloc failed");
2045 if (message && strlen(message) > 253)
2046 debugx(1, DBG_ERR, "ReplyMessage can be at most 253 bytes");
2047 realm->message = message;
2049 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB))
2050 debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2054 if (servers && *servers) {
2055 realm->srvconfs = list_create();
2056 if (!realm->srvconfs)
2057 debugx(1, DBG_ERR, "malloc failed");
2058 for (n = 0; servers[n]; n++) {
2059 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2060 conf = (struct clsrvconf *)entry->data;
2061 if (!strcasecmp(servers[n], conf->name))
2065 debugx(1, DBG_ERR, "addrealm failed, no server %s", servers[n]);
2066 if (!list_push(realm->srvconfs, conf))
2067 debugx(1, DBG_ERR, "malloc failed");
2068 debug(DBG_DBG, "addrealm: added server %s for realm %s", conf->name, value);
2071 realm->srvconfs = NULL;
2073 if (!list_push(realms, realm))
2074 debugx(1, DBG_ERR, "malloc failed");
2075 debug(DBG_DBG, "addrealm: added realm %s", value);
2078 char *parsehostport(char *s, struct clsrvconf *conf) {
2083 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
2087 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
2089 debugx(1, DBG_ERR, "no ] matching initial [");
2093 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
2096 debugx(1, DBG_ERR, "missing host/address");
2098 conf->host = stringcopy(field, p - field);
2101 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
2102 debugx(1, DBG_ERR, "unexpected character after ]");
2105 /* port number or service name is specified */;
2107 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
2109 debugx(1, DBG_ERR, "syntax error, : but no following port");
2110 conf->port = stringcopy(field, p - field);
2112 conf->port = stringcopy(conf->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT, 0);
2116 FILE *openconfigfile(const char *filename) {
2118 char pathname[100], *base = NULL;
2120 f = fopen(filename, "r");
2122 debug(DBG_DBG, "reading config file %s", filename);
2126 if (strlen(filename) + 1 <= sizeof(pathname)) {
2127 /* basename() might modify the string */
2128 strcpy(pathname, filename);
2129 base = basename(pathname);
2130 f = fopen(base, "r");
2134 debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
2136 debug(DBG_DBG, "reading config file %s", base);
2140 struct clsrvconf *server_create(char type) {
2141 struct clsrvconf *conf;
2144 conf = malloc(sizeof(struct clsrvconf));
2146 debugx(1, DBG_ERR, "malloc failed");
2147 memset(conf, 0, sizeof(struct clsrvconf));
2149 lconf = (type == 'T' ? options.listentcp : options.listenudp);
2151 parsehostport(lconf, conf);
2152 if (!strcmp(conf->host, "*")) {
2157 conf->port = stringcopy(type == 'T' ? DEFAULT_TLS_PORT : DEFAULT_UDP_PORT, 0);
2158 if (!resolvepeer(conf, AI_PASSIVE))
2159 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2163 /* returns NULL on error, where to continue parsing if token and ok. E.g. "" will return token with empty string */
2164 char *strtokenquote(char *s, char **token, char *del, char *quote, char *comment) {
2165 char *t = s, *q, *r;
2167 if (!t || !token || !del)
2169 while (*t && strchr(del, *t))
2171 if (!*t || (comment && strchr(comment, *t))) {
2173 return t + 1; /* needs to be non-NULL, but value doesn't matter */
2175 if (quote && (q = strchr(quote, *t))) {
2178 while (*t && *t != *q)
2180 if (!*t || (t[1] && !strchr(del, t[1])))
2188 while (*t && !strchr(del, *t))
2194 /* Parses config with following syntax:
2197 * option-name = value
2199 * option-name value {
2200 * option-name [=] value
2204 void getgeneralconfig(FILE *f, char *block, ...) {
2207 /* initialise lots of stuff to avoid stupid compiler warnings */
2208 char *tokens[3], *s, *opt = NULL, *val = NULL, *word, *optval, **str = NULL, ***mstr = NULL;
2209 int type = 0, tcount, conftype = 0, n;
2210 void (*cbk)(FILE *, char *, char *, char *) = NULL;
2212 while (fgets(line, 1024, f)) {
2214 for (tcount = 0; tcount < 3; tcount++) {
2215 s = strtokenquote(s, &tokens[tcount], " \t\n", "\"'", tcount ? NULL : "#");
2217 debugx(1, DBG_ERR, "Syntax error in line starting with: %s", line);
2218 if (!tokens[tcount])
2221 if (!tcount || **tokens == '#')
2224 if (**tokens == '}') {
2227 debugx(1, DBG_ERR, "configuration error, found } with no matching {");
2234 conftype = CONF_STR;
2237 if (tokens[1][0] == '=' && tokens[1][1] == '\0') {
2240 conftype = CONF_STR;
2243 if (tokens[2][0] == '{' && tokens[2][1] == '\0') {
2246 conftype = CONF_CBK;
2252 debugx(1, DBG_ERR, "configuration error in block %s, line starting with %s", block, tokens[0]);
2253 debugx(1, DBG_ERR, "configuration error, syntax error in line starting with %s", tokens[0]);
2257 debugx(1, DBG_ERR, "configuration error, option %s needs a non-empty value", opt);
2259 va_start(ap, block);
2260 while ((word = va_arg(ap, char *))) {
2261 type = va_arg(ap, int);
2264 str = va_arg(ap, char **);
2266 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2269 mstr = va_arg(ap, char ***);
2271 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2274 cbk = va_arg(ap, void (*)(FILE *, char *, char *, char *));
2277 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2279 if (!strcasecmp(opt, word))
2286 debugx(1, DBG_ERR, "configuration error in block %s, unknown option %s", block, opt);
2287 debugx(1, DBG_ERR, "configuration error, unknown option %s", opt);
2290 if (((type == CONF_STR || type == CONF_MSTR) && conftype != CONF_STR) ||
2291 (type == CONF_CBK && conftype != CONF_CBK)) {
2293 debugx(1, DBG_ERR, "configuration error in block %s, wrong syntax for option %s", block, opt);
2294 debugx(1, DBG_ERR, "configuration error, wrong syntax for option %s", opt);
2300 debug(DBG_DBG, "getgeneralconfig: block %s: %s = %s", block, opt, val);
2302 debug(DBG_DBG, "getgeneralconfig: %s = %s", opt, val);
2303 *str = stringcopy(val, 0);
2305 debugx(1, DBG_ERR, "malloc failed");
2309 debug(DBG_DBG, "getgeneralconfig: block %s: %s = %s", block, opt, val);
2311 debug(DBG_DBG, "getgeneralconfig: %s = %s", opt, val);
2313 for (n = 0; (*mstr)[n]; n++);
2316 *mstr = realloc(*mstr, sizeof(char *) * (n + 2));
2318 debugx(1, DBG_ERR, "malloc failed");
2319 (*mstr)[n] = stringcopy(val, 0);
2320 (*mstr)[n + 1] = NULL;
2323 optval = malloc(strlen(opt) + strlen(val) + 2);
2325 debugx(1, DBG_ERR, "malloc failed");
2326 sprintf(optval, "%s %s", opt, val);
2327 cbk(f, optval, opt, val);
2331 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2336 int addmatchcertattr(struct clsrvconf *conf, char *matchcertattr) {
2339 v = matchcertattr + 20;
2340 if (strncasecmp(matchcertattr, "SubjectAltName:URI:/", 20) || !*v)
2342 /* regexp, remove optional trailing / if present */
2343 if (v[strlen(v) - 1] == '/')
2344 v[strlen(v) - 1] = '\0';
2348 conf->certuriregex = malloc(sizeof(regex_t));
2349 if (!conf->certuriregex) {
2350 debug(DBG_ERR, "malloc failed");
2353 if (regcomp(conf->certuriregex, v, REG_ICASE | REG_NOSUB)) {
2354 regfree(conf->certuriregex);
2355 conf->certuriregex = NULL;
2356 debug(DBG_ERR, "failed to compile regular expression %s", v);
2362 void confclient_cb(FILE *f, char *block, char *opt, char *val) {
2363 char *type = NULL, *tls = NULL, *matchcertattr = NULL;
2364 struct clsrvconf *conf;
2366 debug(DBG_DBG, "confclient_cb called for %s", block);
2368 conf = malloc(sizeof(struct clsrvconf));
2369 if (!conf || !list_push(clconfs, conf))
2370 debugx(1, DBG_ERR, "malloc failed");
2371 memset(conf, 0, sizeof(struct clsrvconf));
2373 getgeneralconfig(f, block,
2374 "type", CONF_STR, &type,
2375 "host", CONF_STR, &conf->host,
2376 "secret", CONF_STR, &conf->secret,
2377 "tls", CONF_STR, &tls,
2378 "matchcertificateattribute", CONF_STR, &matchcertattr,
2382 /* leave conf->name to be NULL for clients */
2384 conf->host = stringcopy(val, 0);
2386 if (type && !strcasecmp(type, "udp")) {
2389 } else if (type && !strcasecmp(type, "tls")) {
2390 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultclient", "default");
2392 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2393 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2394 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2398 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2403 free(matchcertattr);
2405 if (!resolvepeer(conf, 0))
2406 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2408 if (!conf->secret) {
2409 if (conf->type == 'U')
2410 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2411 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2415 void confserver_cb(FILE *f, char *block, char *opt, char *val) {
2416 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *statusserver = NULL;
2417 struct clsrvconf *conf;
2419 debug(DBG_DBG, "confserver_cb called for %s", block);
2421 conf = malloc(sizeof(struct clsrvconf));
2422 if (!conf || !list_push(srvconfs, conf))
2423 debugx(1, DBG_ERR, "malloc failed");
2424 memset(conf, 0, sizeof(struct clsrvconf));
2426 getgeneralconfig(f, block,
2427 "type", CONF_STR, &type,
2428 "host", CONF_STR, &conf->host,
2429 "port", CONF_STR, &conf->port,
2430 "secret", CONF_STR, &conf->secret,
2431 "tls", CONF_STR, &tls,
2432 "matchcertificateattribute", CONF_STR, &matchcertattr,
2433 "StatusServer", CONF_STR, &statusserver,
2437 conf->name = stringcopy(val, 0);
2439 conf->host = stringcopy(val, 0);
2441 if (type && !strcasecmp(type, "udp")) {
2445 conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
2446 } else if (type && !strcasecmp(type, "tls")) {
2447 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultserver", "default");
2449 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2450 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2451 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2453 conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
2457 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2462 free(matchcertattr);
2464 if (!resolvepeer(conf, 0))
2465 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2467 if (!conf->secret) {
2468 if (conf->type == 'U')
2469 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2470 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2474 if (!strcasecmp(statusserver, "on"))
2475 conf->statusserver = 1;
2476 else if (strcasecmp(statusserver, "off"))
2477 debugx(1, DBG_ERR, "error in block %s, StatusServer is %s, must be on or off", block, statusserver);
2482 void confrealm_cb(FILE *f, char *block, char *opt, char *val) {
2483 char **servers = NULL, *msg = NULL;
2485 debug(DBG_DBG, "confrealm_cb called for %s", block);
2487 getgeneralconfig(f, block,
2488 "server", CONF_MSTR, &servers,
2489 "ReplyMessage", CONF_STR, &msg,
2493 addrealm(val, servers, msg);
2497 void conftls_cb(FILE *f, char *block, char *opt, char *val) {
2498 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
2500 debug(DBG_DBG, "conftls_cb called for %s", block);
2502 getgeneralconfig(f, block,
2503 "CACertificateFile", CONF_STR, &cacertfile,
2504 "CACertificatePath", CONF_STR, &cacertpath,
2505 "CertificateFile", CONF_STR, &certfile,
2506 "CertificateKeyFile", CONF_STR, &certkeyfile,
2507 "CertificateKeyPassword", CONF_STR, &certkeypwd,
2511 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
2519 void getmainconfig(const char *configfile) {
2521 char *loglevel = NULL;
2523 f = openconfigfile(configfile);
2524 memset(&options, 0, sizeof(options));
2526 clconfs = list_create();
2528 debugx(1, DBG_ERR, "malloc failed");
2530 srvconfs = list_create();
2532 debugx(1, DBG_ERR, "malloc failed");
2534 realms = list_create();
2536 debugx(1, DBG_ERR, "malloc failed");
2538 tlsconfs = list_create();
2540 debugx(1, DBG_ERR, "malloc failed");
2542 getgeneralconfig(f, NULL,
2543 "ListenUDP", CONF_STR, &options.listenudp,
2544 "ListenTCP", CONF_STR, &options.listentcp,
2545 "LogLevel", CONF_STR, &loglevel,
2546 "LogDestination", CONF_STR, &options.logdestination,
2547 "Client", CONF_CBK, confclient_cb,
2548 "Server", CONF_CBK, confserver_cb,
2549 "Realm", CONF_CBK, confrealm_cb,
2550 "TLS", CONF_CBK, conftls_cb,
2557 if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
2558 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
2559 options.loglevel = *loglevel - '0';
2564 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *loglevel, char **configfile) {
2567 while ((c = getopt(argc, argv, "c:d:fv")) != -1) {
2570 *configfile = optarg;
2573 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
2574 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
2575 *loglevel = *optarg - '0';
2581 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
2586 if (!(argc - optind))
2590 debug(DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -v ]", argv[0]);
2594 int main(int argc, char **argv) {
2595 pthread_t udpserverth;
2596 struct list_node *entry;
2597 uint8_t foreground = 0, loglevel = 0;
2598 char *configfile = NULL;
2600 debug_init("radsecproxy");
2601 debug_set_level(DEBUG_LEVEL);
2602 getargs(argc, argv, &foreground, &loglevel, &configfile);
2604 debug_set_level(loglevel);
2605 getmainconfig(configfile ? configfile : CONFIG_MAIN);
2607 options.loglevel = loglevel;
2608 else if (options.loglevel)
2609 debug_set_level(options.loglevel);
2611 options.logdestination = NULL;
2613 if (!options.logdestination)
2614 options.logdestination = "x-syslog:///";
2615 debug_set_destination(options.logdestination);
2618 if (!list_first(clconfs))
2619 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
2620 if (!list_first(srvconfs))
2621 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
2622 if (!list_first(realms))
2623 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
2625 if (!foreground && (daemon(0, 0) < 0))
2626 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
2628 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
2630 if (client_udp_count) {
2631 udp_server_listen = server_create('U');
2632 udp_server_replyq = newreplyq();
2633 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
2634 debugx(1, DBG_ERR, "pthread_create failed");
2637 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2638 addserver((struct clsrvconf *)entry->data);
2639 if (pthread_create(&((struct clsrvconf *)entry->data)->servers->clientth, NULL, clientwr,
2640 (void *)((struct clsrvconf *)entry->data)->servers))
2641 debugx(1, DBG_ERR, "pthread_create failed");
2644 if (client_tls_count) {
2645 tcp_server_listen = server_create('T');
2646 return tlslistener();
2649 /* just hang around doing nothing, anything to do here? */