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;
136 memset(&hints, 0, sizeof(hints));
137 hints.ai_socktype = (conf->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
138 hints.ai_family = AF_UNSPEC;
139 hints.ai_flags = ai_flags;
140 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
141 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host, conf->port);
146 freeaddrinfo(conf->addrinfo);
147 conf->addrinfo = addrinfo;
151 int connecttoserver(struct addrinfo *addrinfo) {
153 struct addrinfo *res;
156 for (res = addrinfo; res; res = res->ai_next) {
157 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
159 debug(DBG_WARN, "connecttoserver: socket failed");
162 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
164 debug(DBG_WARN, "connecttoserver: connect failed");
171 int bindtoaddr(struct addrinfo *addrinfo) {
173 struct addrinfo *res;
175 for (res = addrinfo; res; res = res->ai_next) {
176 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
178 debug(DBG_WARN, "bindtoaddr: socket failed");
181 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
182 if (!bind(s, res->ai_addr, res->ai_addrlen))
184 debug(DBG_WARN, "bindtoaddr: bind failed");
190 /* returns the peer with matching address, or NULL */
191 /* if conf argument is not NULL, we only check that one */
192 struct clsrvconf *find_peer(char type, struct sockaddr *addr, struct list *confs, struct clsrvconf *conf) {
193 struct sockaddr_in6 *sa6 = NULL;
194 struct in_addr *a4 = NULL;
195 struct addrinfo *res;
196 struct list_node *entry;
198 if (addr->sa_family == AF_INET6) {
199 sa6 = (struct sockaddr_in6 *)addr;
200 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
201 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
203 a4 = &((struct sockaddr_in *)addr)->sin_addr;
206 if (conf->type == type)
207 for (res = conf->addrinfo; res; res = res->ai_next)
208 if ((a4 && res->ai_family == AF_INET &&
209 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
210 (sa6 && res->ai_family == AF_INET6 &&
211 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
216 for (entry = list_first(confs); entry; entry = list_next(entry)) {
217 conf = (struct clsrvconf *)entry->data;
218 if (conf->type == type)
219 for (res = conf->addrinfo; res; res = res->ai_next)
220 if ((a4 && res->ai_family == AF_INET &&
221 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
222 (sa6 && res->ai_family == AF_INET6 &&
223 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
229 struct replyq *newreplyq() {
230 struct replyq *replyq;
232 replyq = malloc(sizeof(struct replyq));
234 debugx(1, DBG_ERR, "malloc failed");
235 replyq->replies = list_create();
236 if (!replyq->replies)
237 debugx(1, DBG_ERR, "malloc failed");
238 pthread_mutex_init(&replyq->mutex, NULL);
239 pthread_cond_init(&replyq->cond, NULL);
243 void addclient(struct clsrvconf *conf) {
245 debug(DBG_ERR, "currently works with just one client per conf");
248 conf->clients = malloc(sizeof(struct client));
249 if (!conf->clients) {
250 debug(DBG_ERR, "malloc failed");
253 memset(conf->clients, 0, sizeof(struct client));
254 conf->clients->conf = conf;
255 conf->clients->replyq = conf->type == 'T' ? newreplyq() : udp_server_replyq;
258 void addserver(struct clsrvconf *conf) {
260 debugx(1, DBG_ERR, "currently works with just one server per conf");
262 conf->servers = malloc(sizeof(struct server));
264 debugx(1, DBG_ERR, "malloc failed");
265 memset(conf->servers, 0, sizeof(struct server));
266 conf->servers->conf = conf;
268 conf->servers->sock = -1;
269 pthread_mutex_init(&conf->servers->lock, NULL);
270 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
271 if (!conf->servers->requests)
272 debugx(1, DBG_ERR, "malloc failed");
273 conf->servers->newrq = 0;
274 pthread_mutex_init(&conf->servers->newrq_mutex, NULL);
275 pthread_cond_init(&conf->servers->newrq_cond, NULL);
278 /* exactly one of client and server must be non-NULL */
279 /* should probably take peer list (client(s) or server(s)) as argument instead */
280 /* if *peer == NULL we return who we received from, else require it to be from peer */
281 /* return from in sa if not NULL */
282 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
284 unsigned char buf[65536], *rad;
285 struct sockaddr_storage from;
286 socklen_t fromlen = sizeof(from);
290 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
292 debug(DBG_WARN, "radudpget: recv failed");
295 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
298 debug(DBG_WARN, "radudpget: packet too small");
304 debug(DBG_WARN, "radudpget: length too small");
309 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
313 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
317 p = find_peer('U', (struct sockaddr *)&from, NULL, (*client)->conf);
319 p = find_peer('U', (struct sockaddr *)&from, clconfs, NULL);
322 p = find_peer('U', (struct sockaddr *)&from, NULL, (*server)->conf);
324 p = find_peer('U', (struct sockaddr *)&from, srvconfs, NULL);
327 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer, ignoring");
333 debug(DBG_ERR, "radudpget: malloc failed");
337 if (client && !*client) {
344 *client = p->clients;
345 } else if (server && !*server)
346 *server = p->servers;
350 memcpy(rad, buf, len);
356 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
357 int loc, i, l, n, r = 0;
360 STACK_OF(GENERAL_NAME) *alt;
363 debug(DBG_DBG, "subjectaltnameaddr");
365 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
369 ex = X509_get_ext(cert, loc);
370 alt = X509V3_EXT_d2i(ex);
374 n = sk_GENERAL_NAME_num(alt);
375 for (i = 0; i < n; i++) {
376 gn = sk_GENERAL_NAME_value(alt, i);
377 if (gn->type != GEN_IPADD)
380 v = (char *)ASN1_STRING_data(gn->d.ia5);
381 l = ASN1_STRING_length(gn->d.ia5);
382 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
383 && !memcmp(v, &addr, l)) {
388 GENERAL_NAMES_free(alt);
392 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
393 int loc, i, l, n, r = 0;
396 STACK_OF(GENERAL_NAME) *alt;
399 debug(DBG_DBG, "subjectaltnameregexp");
401 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
405 ex = X509_get_ext(cert, loc);
406 alt = X509V3_EXT_d2i(ex);
410 n = sk_GENERAL_NAME_num(alt);
411 for (i = 0; i < n; i++) {
412 gn = sk_GENERAL_NAME_value(alt, i);
413 if (gn->type != type)
416 v = (char *)ASN1_STRING_data(gn->d.ia5);
417 l = ASN1_STRING_length(gn->d.ia5);
421 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
424 if (memcmp(v, exact, l))
427 s = stringcopy((char *)v, l);
429 debug(DBG_ERR, "malloc failed");
432 if (regexec(regex, s, 0, NULL, 0)) {
441 GENERAL_NAMES_free(alt);
445 int tlsverifycert(SSL *ssl, struct clsrvconf *conf) {
452 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
454 struct in6_addr addr;
456 if (SSL_get_verify_result(ssl) != X509_V_OK) {
457 debug(DBG_ERR, "tlsverifycert: basic validation failed");
458 while ((error = ERR_get_error()))
459 debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
463 cert = SSL_get_peer_certificate(ssl);
465 debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
469 if (inet_pton(AF_INET, conf->host, &addr))
471 else if (inet_pton(AF_INET6, conf->host, &addr))
474 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
478 debug(DBG_DBG, "tlsverifycert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
481 debug(DBG_DBG, "tlsverifycert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
483 nm = X509_get_subject_name(cert);
486 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
489 e = X509_NAME_get_entry(nm, loc);
490 s = X509_NAME_ENTRY_get_data(e);
491 v = (char *) ASN1_STRING_data(s);
492 l = ASN1_STRING_length(s);
496 printfchars(NULL, "cn", NULL, v, l);
498 if (l == strlen(conf->host) && !strncasecmp(conf->host, v, l)) {
500 debug(DBG_DBG, "tlsverifycert: Found cn matching host %s", conf->host);
506 debug(DBG_ERR, "tlsverifycert: cn not matching host %s", conf->host);
510 if (conf->certuriregex) {
511 r = subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex);
513 debug(DBG_DBG, "tlsverifycert: subjectaltname URI not matching regex");
517 debug(DBG_DBG, "tlsverifycert: subjectaltname URI matching regex");
523 void tlsconnect(struct server *server, struct timeval *when, char *text) {
527 debug(DBG_DBG, "tlsconnect called from %s", text);
528 pthread_mutex_lock(&server->lock);
529 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
530 /* already reconnected, nothing to do */
531 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
532 pthread_mutex_unlock(&server->lock);
536 debug(DBG_DBG, "tlsconnect %s", text);
539 gettimeofday(&now, NULL);
540 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
541 if (server->connectionok) {
542 server->connectionok = 0;
544 } else if (elapsed < 5)
546 else if (elapsed < 300) {
547 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
549 } else if (elapsed < 100000) {
550 debug(DBG_INFO, "tlsconnect: sleeping %ds", 600);
553 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
554 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
555 if (server->sock >= 0)
557 if ((server->sock = connecttoserver(server->conf->addrinfo)) < 0) {
558 debug(DBG_ERR, "tlsconnect: connecttoserver failed");
562 SSL_free(server->ssl);
563 server->ssl = SSL_new(server->conf->ssl_ctx);
564 SSL_set_fd(server->ssl, server->sock);
565 if (SSL_connect(server->ssl) > 0 && tlsverifycert(server->ssl, server->conf))
568 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
569 gettimeofday(&server->lastconnecttry, NULL);
570 pthread_mutex_unlock(&server->lock);
573 unsigned char *radtlsget(SSL *ssl) {
575 unsigned char buf[4], *rad;
578 for (total = 0; total < 4; total += cnt) {
579 cnt = SSL_read(ssl, buf + total, 4 - total);
581 debug(DBG_ERR, "radtlsget: connection lost");
582 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
583 /* remote end sent close_notify, send one back */
593 debug(DBG_ERR, "radtlsget: malloc failed");
598 for (; total < len; total += cnt) {
599 cnt = SSL_read(ssl, rad + total, len - total);
601 debug(DBG_ERR, "radtlsget: connection lost");
602 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
603 /* remote end sent close_notify, send one back */
615 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
618 debug(DBG_DBG, "radtlsget: got %d bytes", total);
622 int clientradput(struct server *server, unsigned char *rad) {
626 struct timeval lastconnecttry;
629 if (server->conf->type == 'U') {
630 if (send(server->sock, rad, len, 0) >= 0) {
631 debug(DBG_DBG, "clienradput: sent UDP of length %d to %s port %s", len, server->conf->host, server->conf->port);
634 debug(DBG_WARN, "clientradput: send failed");
638 lastconnecttry = server->lastconnecttry;
639 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
640 while ((error = ERR_get_error()))
641 debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
642 tlsconnect(server, &lastconnecttry, "clientradput");
643 lastconnecttry = server->lastconnecttry;
646 server->connectionok = 1;
647 debug(DBG_DBG, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s",
648 cnt, len, server->conf->host);
652 int radsign(unsigned char *rad, unsigned char *sec) {
653 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
654 static unsigned char first = 1;
655 static EVP_MD_CTX mdctx;
659 pthread_mutex_lock(&lock);
661 EVP_MD_CTX_init(&mdctx);
665 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
666 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
667 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
668 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
670 pthread_mutex_unlock(&lock);
674 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
675 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
676 static unsigned char first = 1;
677 static EVP_MD_CTX mdctx;
678 unsigned char hash[EVP_MAX_MD_SIZE];
682 pthread_mutex_lock(&lock);
684 EVP_MD_CTX_init(&mdctx);
690 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
691 EVP_DigestUpdate(&mdctx, rad, 4) &&
692 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
693 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
694 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
695 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
697 !memcmp(hash, rad + 4, 16));
698 pthread_mutex_unlock(&lock);
702 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
703 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
704 static unsigned char first = 1;
705 static HMAC_CTX hmacctx;
707 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
709 pthread_mutex_lock(&lock);
711 HMAC_CTX_init(&hmacctx);
715 memcpy(auth, authattr, 16);
716 memset(authattr, 0, 16);
718 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
719 HMAC_Update(&hmacctx, rad, RADLEN(rad));
720 HMAC_Final(&hmacctx, hash, &md_len);
721 memcpy(authattr, auth, 16);
723 debug(DBG_WARN, "message auth computation failed");
724 pthread_mutex_unlock(&lock);
728 if (memcmp(auth, hash, 16)) {
729 debug(DBG_WARN, "message authenticator, wrong value");
730 pthread_mutex_unlock(&lock);
734 pthread_mutex_unlock(&lock);
738 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
739 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
740 static unsigned char first = 1;
741 static HMAC_CTX hmacctx;
747 pthread_mutex_lock(&lock);
749 HMAC_CTX_init(&hmacctx);
753 memset(authattrval, 0, 16);
755 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
756 HMAC_Update(&hmacctx, rad, RADLEN(rad));
757 HMAC_Final(&hmacctx, authattrval, &md_len);
759 debug(DBG_WARN, "message auth computation failed");
760 pthread_mutex_unlock(&lock);
764 pthread_mutex_unlock(&lock);
768 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
770 if (ATTRTYPE(attrs) == type)
772 length -= ATTRLEN(attrs);
773 attrs += ATTRLEN(attrs);
778 void sendrq(struct server *to, struct request *rq) {
782 pthread_mutex_lock(&to->newrq_mutex);
783 /* might simplify if only try nextid, might be ok */
784 for (i = to->nextid; i < MAX_REQUESTS; i++)
785 if (!to->requests[i].buf)
787 if (i == MAX_REQUESTS) {
788 for (i = 0; i < to->nextid; i++)
789 if (!to->requests[i].buf)
791 if (i == to->nextid) {
792 debug(DBG_WARN, "No room in queue, dropping request");
794 pthread_mutex_unlock(&to->newrq_mutex);
799 rq->buf[1] = (char)i;
801 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
802 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
804 pthread_mutex_unlock(&to->newrq_mutex);
808 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
809 to->requests[i] = *rq;
814 debug(DBG_DBG, "signalling client writer");
815 pthread_cond_signal(&to->newrq_cond);
817 pthread_mutex_unlock(&to->newrq_mutex);
820 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
824 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
826 debug(DBG_WARN, "sendreply: failed to sign message");
830 reply = malloc(sizeof(struct reply));
833 debug(DBG_ERR, "sendreply: malloc failed");
836 memset(reply, 0, sizeof(struct reply));
841 pthread_mutex_lock(&to->replyq->mutex);
843 first = list_first(to->replyq->replies) == NULL;
845 if (!list_push(to->replyq->replies, reply)) {
846 pthread_mutex_unlock(&to->replyq->mutex);
849 debug(DBG_ERR, "sendreply: malloc failed");
854 debug(DBG_DBG, "signalling server writer");
855 pthread_cond_signal(&to->replyq->cond);
857 pthread_mutex_unlock(&to->replyq->mutex);
860 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
861 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
862 static unsigned char first = 1;
863 static EVP_MD_CTX mdctx;
864 unsigned char hash[EVP_MAX_MD_SIZE], *input;
866 uint8_t i, offset = 0, out[128];
868 pthread_mutex_lock(&lock);
870 EVP_MD_CTX_init(&mdctx);
876 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
877 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
878 !EVP_DigestUpdate(&mdctx, input, 16) ||
879 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
881 pthread_mutex_unlock(&lock);
884 for (i = 0; i < 16; i++)
885 out[offset + i] = hash[i] ^ in[offset + i];
886 input = out + offset - 16;
891 memcpy(in, out, len);
892 pthread_mutex_unlock(&lock);
896 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
897 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
898 static unsigned char first = 1;
899 static EVP_MD_CTX mdctx;
900 unsigned char hash[EVP_MAX_MD_SIZE], *input;
902 uint8_t i, offset = 0, out[128];
904 pthread_mutex_lock(&lock);
906 EVP_MD_CTX_init(&mdctx);
912 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
913 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
914 !EVP_DigestUpdate(&mdctx, input, 16) ||
915 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
917 pthread_mutex_unlock(&lock);
920 for (i = 0; i < 16; i++)
921 out[offset + i] = hash[i] ^ in[offset + i];
927 memcpy(in, out, len);
928 pthread_mutex_unlock(&lock);
932 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
933 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
934 static unsigned char first = 1;
935 static EVP_MD_CTX mdctx;
936 unsigned char hash[EVP_MAX_MD_SIZE];
940 pthread_mutex_lock(&lock);
942 EVP_MD_CTX_init(&mdctx);
947 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
948 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
949 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
952 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
953 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
954 !EVP_DigestUpdate(&mdctx, auth, 16) ||
955 !EVP_DigestUpdate(&mdctx, salt, 2) ||
956 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
957 pthread_mutex_unlock(&lock);
962 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
965 for (i = 0; i < 16; i++)
968 for (offset = 16; offset < len; offset += 16) {
970 printf("text + offset - 16 c(%d): ", offset / 16);
971 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
973 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
974 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
975 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
976 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
978 pthread_mutex_unlock(&lock);
982 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
985 for (i = 0; i < 16; i++)
986 text[offset + i] ^= hash[i];
990 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
993 pthread_mutex_unlock(&lock);
997 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
998 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
999 static unsigned char first = 1;
1000 static EVP_MD_CTX mdctx;
1001 unsigned char hash[EVP_MAX_MD_SIZE];
1002 unsigned int md_len;
1006 pthread_mutex_lock(&lock);
1008 EVP_MD_CTX_init(&mdctx);
1013 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1014 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1015 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1018 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1019 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1020 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1021 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1022 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1023 pthread_mutex_unlock(&lock);
1028 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1031 for (i = 0; i < 16; i++)
1032 plain[i] = text[i] ^ hash[i];
1034 for (offset = 16; offset < len; offset += 16) {
1036 printf("text + offset - 16 c(%d): ", offset / 16);
1037 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1039 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1040 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1041 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1042 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1044 pthread_mutex_unlock(&lock);
1048 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1051 for (i = 0; i < 16; i++)
1052 plain[offset + i] = text[offset + i] ^ hash[i];
1055 memcpy(text, plain, len);
1057 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1060 pthread_mutex_unlock(&lock);
1064 struct realm *id2realm(char *id, uint8_t len) {
1065 struct list_node *entry;
1066 struct realm *realm;
1068 for (entry = list_first(realms); entry; entry = list_next(entry)) {
1069 realm = (struct realm *)entry->data;
1070 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1071 debug(DBG_DBG, "found matching realm: %s", realm->name);
1078 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
1081 pthread_mutex_lock(&to->newrq_mutex);
1082 for (i = 0; i < MAX_REQUESTS; i++)
1083 if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
1085 pthread_mutex_unlock(&to->newrq_mutex);
1087 return i < MAX_REQUESTS;
1090 int attrvalidate(unsigned char *attrs, int length) {
1091 while (length > 1) {
1092 if (ATTRLEN(attrs) < 2) {
1093 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1096 length -= ATTRLEN(attrs);
1098 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1101 attrs += ATTRLEN(attrs);
1104 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1108 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1109 if (len < 16 || len > 128 || len % 16) {
1110 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1114 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1115 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1119 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1121 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1122 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1128 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1131 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1132 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1135 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1136 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1142 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1143 char *oldsecret, char *newsecret) {
1144 unsigned char *attr;
1146 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1147 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1148 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1154 void respondstatusserver(struct request *rq) {
1155 unsigned char *resp;
1159 debug(DBG_ERR, "respondstatusserver: malloc failed");
1162 memcpy(resp, rq->buf, 20);
1163 resp[0] = RAD_Access_Accept;
1166 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1167 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1170 void respondreject(struct request *rq, char *message) {
1171 unsigned char *resp;
1175 len += 2 + strlen(message);
1179 debug(DBG_ERR, "respondreject: malloc failed");
1182 memcpy(resp, rq->buf, 20);
1183 resp[0] = RAD_Access_Reject;
1184 *(uint16_t *)(resp + 2) = htons(len);
1186 resp[20] = RAD_Attr_Reply_Message;
1187 resp[21] = len - 20;
1188 memcpy(resp + 22, message, len - 22);
1190 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1193 void radsrv(struct request *rq) {
1194 uint8_t code, id, *auth, *attrs, *attr;
1196 struct server *to = NULL;
1198 unsigned char *buf, newauth[16];
1199 struct realm *realm = NULL;
1202 code = *(uint8_t *)buf;
1203 id = *(uint8_t *)(buf + 1);
1205 auth = (uint8_t *)(buf + 4);
1207 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1209 if (code != RAD_Access_Request && code != RAD_Status_Server) {
1210 debug(DBG_INFO, "radsrv: server currently accepts only access-requests and status-server, ignoring");
1218 if (!attrvalidate(attrs, len)) {
1219 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1224 if (code == RAD_Access_Request) {
1225 attr = attrget(attrs, len, RAD_Attr_User_Name);
1227 debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1231 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1232 username[ATTRVALLEN(attr)] = '\0';
1233 debug(DBG_DBG, "Access Request with username: %s", username);
1235 realm = id2realm(username, strlen(username));
1237 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1241 to = realm->srvconf->servers;
1243 if (to && rqinqueue(to, rq->from, id)) {
1244 debug(DBG_INFO, "radsrv: already got request from host %s with id %d, ignoring", rq->from->conf->host, id);
1250 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1251 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(buf, ATTRVAL(attr), rq->from->conf->secret))) {
1252 debug(DBG_WARN, "radsrv: message authentication failed");
1257 if (code == RAD_Status_Server) {
1258 respondstatusserver(rq);
1263 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, username);
1264 respondreject(rq, realm->message);
1268 if (!RAND_bytes(newauth, 16)) {
1269 debug(DBG_WARN, "radsrv: failed to generate random auth");
1275 printfchars(NULL, "auth", "%02x ", auth, 16);
1278 attr = attrget(attrs, len, RAD_Attr_User_Password);
1280 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1281 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1287 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1289 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1290 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1297 memcpy(rq->origauth, auth, 16);
1298 memcpy(auth, newauth, 16);
1302 void *clientrd(void *arg) {
1303 struct server *server = (struct server *)arg;
1304 struct client *from;
1306 unsigned char *buf, *messageauth, *subattrs, *attrs, *attr;
1307 struct sockaddr_storage fromsa;
1308 struct timeval lastconnecttry;
1312 lastconnecttry = server->lastconnecttry;
1313 buf = (server->conf->type == 'U' ? radudpget(server->sock, NULL, &server, NULL) : radtlsget(server->ssl));
1314 if (!buf && server->conf->type == 'T') {
1315 tlsconnect(server, &lastconnecttry, "clientrd");
1319 server->connectionok = 1;
1321 i = buf[1]; /* i is the id */
1324 case RAD_Access_Accept:
1325 debug(DBG_DBG, "got Access Accept with id %d", i);
1327 case RAD_Access_Reject:
1328 debug(DBG_DBG, "got Access Reject with id %d", i);
1330 case RAD_Access_Challenge:
1331 debug(DBG_DBG, "got Access Challenge with id %d", i);
1335 debug(DBG_INFO, "clientrd: discarding, only accept access accept, access reject and access challenge messages");
1339 pthread_mutex_lock(&server->newrq_mutex);
1340 if (!server->requests[i].buf || !server->requests[i].tries) {
1341 pthread_mutex_unlock(&server->newrq_mutex);
1343 debug(DBG_INFO, "clientrd: no matching request sent with this id, ignoring");
1347 if (server->requests[i].received) {
1348 pthread_mutex_unlock(&server->newrq_mutex);
1350 debug(DBG_INFO, "clientrd: already received, ignoring");
1354 if (!validauth(buf, server->requests[i].buf + 4, (unsigned char *)server->conf->secret)) {
1355 pthread_mutex_unlock(&server->newrq_mutex);
1357 debug(DBG_WARN, "clientrd: invalid auth, ignoring");
1361 from = server->requests[i].from;
1362 len = RADLEN(buf) - 20;
1365 if (!attrvalidate(attrs, len)) {
1366 pthread_mutex_unlock(&server->newrq_mutex);
1368 debug(DBG_WARN, "clientrd: attribute validation failed, ignoring packet");
1372 /* Message Authenticator */
1373 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1375 if (ATTRVALLEN(messageauth) != 16) {
1376 pthread_mutex_unlock(&server->newrq_mutex);
1378 debug(DBG_WARN, "clientrd: illegal message auth attribute length, ignoring packet");
1381 memcpy(tmp, buf + 4, 16);
1382 memcpy(buf + 4, server->requests[i].buf + 4, 16);
1383 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
1384 pthread_mutex_unlock(&server->newrq_mutex);
1386 debug(DBG_WARN, "clientrd: message authentication failed");
1389 memcpy(buf + 4, tmp, 16);
1390 debug(DBG_DBG, "clientrd: message auth ok");
1393 if (*server->requests[i].buf == RAD_Status_Server) {
1394 server->requests[i].received = 1;
1395 pthread_mutex_unlock(&server->newrq_mutex);
1397 debug(DBG_INFO, "clientrd: got status server response from %s", server->conf->host);
1402 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1403 if (ATTRVALLEN(attr) <= 4)
1406 if (((uint16_t *)attr)[1] != 0 || ntohs(((uint16_t *)attr)[2]) != 311) /* 311 == MS */
1409 sublen = ATTRVALLEN(attr) - 4;
1410 subattrs = ATTRVAL(attr) + 4;
1411 if (!attrvalidate(subattrs, sublen) ||
1412 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1413 server->requests + i, server->conf->secret, from->conf->secret) ||
1414 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1415 server->requests + i, server->conf->secret, from->conf->secret))
1419 pthread_mutex_unlock(&server->newrq_mutex);
1421 debug(DBG_WARN, "clientrd: MS attribute handling failed, ignoring packet");
1425 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject) {
1426 attr = attrget(server->requests[i].buf + 20, RADLEN(server->requests[i].buf) - 20, RAD_Attr_User_Name);
1427 /* we know the attribute exists */
1428 memcpy(tmp, ATTRVAL(attr), ATTRVALLEN(attr));
1429 tmp[ATTRVALLEN(attr)] = '\0';
1431 case RAD_Access_Accept:
1432 debug(DBG_INFO, "Access Accept for %s from %s", tmp, server->conf->host);
1434 case RAD_Access_Reject:
1435 debug(DBG_INFO, "Access Reject for %s from %s", tmp, server->conf->host);
1440 /* once we set received = 1, requests[i] may be reused */
1441 buf[1] = (char)server->requests[i].origid;
1442 memcpy(buf + 4, server->requests[i].origauth, 16);
1444 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1448 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
1449 pthread_mutex_unlock(&server->newrq_mutex);
1453 debug(DBG_DBG, "clientrd: computed messageauthattr");
1456 if (from->conf->type == 'U')
1457 fromsa = server->requests[i].fromsa;
1458 server->requests[i].received = 1;
1459 pthread_mutex_unlock(&server->newrq_mutex);
1461 debug(DBG_DBG, "clientrd: giving packet back to where it came from");
1462 sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
1466 void *clientwr(void *arg) {
1467 struct server *server = (struct server *)arg;
1469 pthread_t clientrdth;
1472 struct timeval now, lastsend;
1473 struct timespec timeout;
1474 struct request statsrvrq;
1475 unsigned char statsrvbuf[38];
1477 memset(&timeout, 0, sizeof(struct timespec));
1479 if (server->conf->statusserver) {
1480 memset(&statsrvrq, 0, sizeof(struct request));
1481 memset(statsrvbuf, 0, sizeof(statsrvbuf));
1482 statsrvbuf[0] = RAD_Status_Server;
1484 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
1485 statsrvbuf[21] = 18;
1486 gettimeofday(&lastsend, NULL);
1489 if (server->conf->type == 'U') {
1490 if ((server->sock = connecttoserver(server->conf->addrinfo)) < 0)
1491 debugx(1, DBG_ERR, "clientwr: connecttoserver failed");
1493 tlsconnect(server, NULL, "new client");
1495 if (pthread_create(&clientrdth, NULL, clientrd, (void *)server))
1496 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
1499 pthread_mutex_lock(&server->newrq_mutex);
1500 if (!server->newrq) {
1501 gettimeofday(&now, NULL);
1502 if (server->conf->statusserver) {
1503 /* random 0-7 seconds */
1504 RAND_bytes(&rnd, 1);
1506 if (!timeout.tv_sec || timeout.tv_sec - now.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
1507 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
1509 if (timeout.tv_sec) {
1510 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1511 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1514 debug(DBG_DBG, "clientwr: waiting for new request");
1515 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1518 if (server->newrq) {
1519 debug(DBG_DBG, "clientwr: got new request");
1522 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1523 pthread_mutex_unlock(&server->newrq_mutex);
1525 for (i = 0; i < MAX_REQUESTS; i++) {
1526 pthread_mutex_lock(&server->newrq_mutex);
1527 while (i < MAX_REQUESTS && !server->requests[i].buf)
1529 if (i == MAX_REQUESTS) {
1530 pthread_mutex_unlock(&server->newrq_mutex);
1533 rq = server->requests + i;
1536 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
1538 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
1540 /* setting this to NULL means that it can be reused */
1543 pthread_mutex_unlock(&server->newrq_mutex);
1547 gettimeofday(&now, NULL);
1548 if (now.tv_sec < rq->expiry.tv_sec) {
1549 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1550 timeout.tv_sec = rq->expiry.tv_sec;
1551 pthread_mutex_unlock(&server->newrq_mutex);
1555 if (rq->tries == (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
1556 ? 1 : REQUEST_RETRIES)) {
1557 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1558 if (*rq->buf == RAD_Status_Server)
1559 debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->conf->host);
1561 /* setting this to NULL means that it can be reused */
1563 pthread_mutex_unlock(&server->newrq_mutex);
1566 pthread_mutex_unlock(&server->newrq_mutex);
1568 rq->expiry.tv_sec = now.tv_sec +
1569 (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
1570 ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
1571 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1572 timeout.tv_sec = rq->expiry.tv_sec;
1574 clientradput(server, server->requests[i].buf);
1575 gettimeofday(&lastsend, NULL);
1577 if (server->conf->statusserver) {
1578 gettimeofday(&now, NULL);
1579 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
1580 if (!RAND_bytes(statsrvbuf + 4, 16)) {
1581 debug(DBG_WARN, "clientwr: failed to generate random auth");
1584 statsrvrq.buf = malloc(sizeof(statsrvbuf));
1585 if (!statsrvrq.buf) {
1586 debug(DBG_ERR, "clientwr: malloc failed");
1589 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
1590 debug(DBG_DBG, "clientwr: sending status server to %s", server->conf->host);
1591 lastsend.tv_sec = now.tv_sec;
1592 sendrq(server, &statsrvrq);
1598 void *udpserverwr(void *arg) {
1599 struct replyq *replyq = udp_server_replyq;
1600 struct reply *reply;
1603 pthread_mutex_lock(&replyq->mutex);
1604 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
1605 debug(DBG_DBG, "udp server writer, waiting for signal");
1606 pthread_cond_wait(&replyq->cond, &replyq->mutex);
1607 debug(DBG_DBG, "udp server writer, got signal");
1609 pthread_mutex_unlock(&replyq->mutex);
1611 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
1612 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
1613 debug(DBG_WARN, "sendudp: send failed");
1619 void *udpserverrd(void *arg) {
1621 pthread_t udpserverwrth;
1623 if ((udp_server_sock = bindtoaddr(udp_server_listen->addrinfo)) < 0)
1624 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
1626 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
1627 udp_server_listen->host ? udp_server_listen->host : "*", udp_server_listen->port);
1629 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
1630 debugx(1, DBG_ERR, "pthread_create failed");
1633 memset(&rq, 0, sizeof(struct request));
1634 rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
1639 void *tlsserverwr(void *arg) {
1641 unsigned long error;
1642 struct client *client = (struct client *)arg;
1643 struct replyq *replyq;
1644 struct reply *reply;
1646 debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
1647 replyq = client->replyq;
1649 pthread_mutex_lock(&replyq->mutex);
1650 while (!list_first(replyq->replies)) {
1652 debug(DBG_DBG, "tls server writer, waiting for signal");
1653 pthread_cond_wait(&replyq->cond, &replyq->mutex);
1654 debug(DBG_DBG, "tls server writer, got signal");
1657 /* ssl might have changed while waiting */
1658 pthread_mutex_unlock(&replyq->mutex);
1659 debug(DBG_DBG, "tlsserverwr: exiting as requested");
1663 reply = (struct reply *)list_shift(replyq->replies);
1664 pthread_mutex_unlock(&replyq->mutex);
1665 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
1667 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
1668 cnt, RADLEN(reply->buf));
1670 while ((error = ERR_get_error()))
1671 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
1677 void *tlsserverrd(void *arg) {
1679 unsigned long error;
1681 struct client *client = (struct client *)arg;
1682 pthread_t tlsserverwrth;
1685 debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
1688 if (SSL_accept(ssl) <= 0) {
1689 while ((error = ERR_get_error()))
1690 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
1691 debug(DBG_ERR, "SSL_accept failed");
1694 if (tlsverifycert(client->ssl, client->conf)) {
1695 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
1696 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
1700 memset(&rq, 0, sizeof(struct request));
1701 rq.buf = radtlsget(client->ssl);
1704 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
1708 debug(DBG_ERR, "tlsserverrd: connection lost");
1709 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
1711 pthread_mutex_lock(&client->replyq->mutex);
1712 pthread_cond_signal(&client->replyq->cond);
1713 pthread_mutex_unlock(&client->replyq->mutex);
1714 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
1715 pthread_join(tlsserverwrth, NULL);
1719 s = SSL_get_fd(ssl);
1721 shutdown(s, SHUT_RDWR);
1723 debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->conf->host);
1729 pthread_t tlsserverth;
1731 struct sockaddr_storage from;
1732 size_t fromlen = sizeof(from);
1733 struct clsrvconf *conf;
1734 struct client *client;
1736 if ((s = bindtoaddr(tcp_server_listen->addrinfo)) < 0)
1737 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
1740 debug(DBG_WARN, "listening for incoming TCP on %s:%s",
1741 tcp_server_listen->host ? tcp_server_listen->host : "*", tcp_server_listen->port);
1744 snew = accept(s, (struct sockaddr *)&from, &fromlen);
1746 debug(DBG_WARN, "accept failed");
1749 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
1751 conf = find_peer('T', (struct sockaddr *)&from, clconfs, NULL);
1753 debug(DBG_WARN, "ignoring request, not a known TLS client");
1754 shutdown(snew, SHUT_RDWR);
1761 client = conf->clients;
1763 if (!client || client->ssl) {
1765 debug(DBG_WARN, "Ignoring incoming TLS connection, already have one from this client");
1766 shutdown(snew, SHUT_RDWR);
1770 client->ssl = SSL_new(client->conf->ssl_ctx);
1771 SSL_set_fd(client->ssl, snew);
1772 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
1773 debug(DBG_ERR, "tlslistener: pthread_create failed");
1774 SSL_free(client->ssl);
1775 shutdown(snew, SHUT_RDWR);
1780 pthread_detach(tlsserverth);
1785 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
1789 unsigned long error;
1791 if (!certfile || !certkeyfile)
1792 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
1794 if (!cacertfile && !cacertpath)
1795 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
1798 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
1799 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
1800 for (i = 0; i < CRYPTO_num_locks(); i++) {
1801 ssl_lock_count[i] = 0;
1802 pthread_mutex_init(&ssl_locks[i], NULL);
1804 CRYPTO_set_id_callback(ssl_thread_id);
1805 CRYPTO_set_locking_callback(ssl_locking_callback);
1807 SSL_load_error_strings();
1810 while (!RAND_status()) {
1811 time_t t = time(NULL);
1812 pid_t pid = getpid();
1813 RAND_seed((unsigned char *)&t, sizeof(time_t));
1814 RAND_seed((unsigned char *)&pid, sizeof(pid));
1817 ctx = SSL_CTX_new(TLSv1_method());
1819 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
1820 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
1822 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
1823 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
1824 !SSL_CTX_check_private_key(ctx) ||
1825 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
1826 while ((error = ERR_get_error()))
1827 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
1828 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
1831 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
1832 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
1834 new = malloc(sizeof(struct tls));
1835 if (!new || !list_push(tlsconfs, new))
1836 debugx(1, DBG_ERR, "malloc failed");
1838 memset(new, 0, sizeof(struct tls));
1839 new->name = stringcopy(value, 0);
1841 debugx(1, DBG_ERR, "malloc failed");
1844 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
1848 struct list_node *entry;
1851 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
1852 t = (struct tls *)entry->data;
1856 SSL_CTX_free(t->ctx);
1858 list_destroy(tlsconfs);
1862 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
1863 struct list_node *entry;
1864 struct tls *t, *t1 = NULL, *t2 = NULL;
1866 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
1867 t = (struct tls *)entry->data;
1868 if (!strcasecmp(t->name, alt1)) {
1872 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
1883 void addrealm(char *value, char *server, char *message) {
1885 struct realm *realm;
1886 char *s, *regex = NULL;
1887 struct list_node *entry;
1888 struct clsrvconf *conf;
1891 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1892 conf = (struct clsrvconf *)entry->data;
1893 if (!strcasecmp(server, conf->name))
1897 debugx(1, DBG_ERR, "addrealm failed, no server %s", server);
1900 if (*value == '/') {
1901 /* regexp, remove optional trailing / if present */
1902 if (value[strlen(value) - 1] == '/')
1903 value[strlen(value) - 1] = '\0';
1905 /* not a regexp, let us make it one */
1906 if (*value == '*' && !value[1])
1907 regex = stringcopy(".*", 0);
1909 for (n = 0, s = value; *s;)
1912 regex = malloc(strlen(value) + n + 3);
1915 for (n = 1, s = value; *s; s++) {
1925 debugx(1, DBG_ERR, "malloc failed");
1926 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
1929 realm = malloc(sizeof(struct realm));
1930 if (!realm || !list_push(realms, realm))
1931 debugx(1, DBG_ERR, "malloc failed");
1933 memset(realm, 0, sizeof(struct realm));
1934 realm->name = stringcopy(value, 0);
1936 debugx(1, DBG_ERR, "malloc failed");
1937 if (message && strlen(message) > 253)
1938 debugx(1, DBG_ERR, "ReplyMessage can be at most 253 bytes");
1939 realm->message = message;
1941 realm->srvconf = conf;
1942 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB))
1943 debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
1946 debug(DBG_DBG, "addrealm: added realm %s for server %s", value, server);
1949 char *parsehostport(char *s, struct clsrvconf *conf) {
1954 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
1958 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1960 debugx(1, DBG_ERR, "no ] matching initial [");
1964 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1967 debugx(1, DBG_ERR, "missing host/address");
1969 conf->host = stringcopy(field, p - field);
1972 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
1973 debugx(1, DBG_ERR, "unexpected character after ]");
1976 /* port number or service name is specified */;
1978 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1980 debugx(1, DBG_ERR, "syntax error, : but no following port");
1981 conf->port = stringcopy(field, p - field);
1983 conf->port = stringcopy(conf->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT, 0);
1987 FILE *openconfigfile(const char *filename) {
1989 char pathname[100], *base = NULL;
1991 f = fopen(filename, "r");
1993 debug(DBG_DBG, "reading config file %s", filename);
1997 if (strlen(filename) + 1 <= sizeof(pathname)) {
1998 /* basename() might modify the string */
1999 strcpy(pathname, filename);
2000 base = basename(pathname);
2001 f = fopen(base, "r");
2005 debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
2007 debug(DBG_DBG, "reading config file %s", base);
2011 struct clsrvconf *server_create(char type) {
2012 struct clsrvconf *conf;
2015 conf = malloc(sizeof(struct clsrvconf));
2017 debugx(1, DBG_ERR, "malloc failed");
2018 memset(conf, 0, sizeof(struct clsrvconf));
2020 lconf = (type == 'T' ? options.listentcp : options.listenudp);
2022 parsehostport(lconf, conf);
2023 if (!strcmp(conf->host, "*")) {
2028 conf->port = stringcopy(type == 'T' ? DEFAULT_TLS_PORT : DEFAULT_UDP_PORT, 0);
2029 if (!resolvepeer(conf, AI_PASSIVE))
2030 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2034 /* returns NULL on error, where to continue parsing if token and ok. E.g. "" will return token with empty string */
2035 char *strtokenquote(char *s, char **token, char *del, char *quote, char *comment) {
2036 char *t = s, *q, *r;
2038 if (!t || !token || !del)
2040 while (*t && strchr(del, *t))
2042 if (!*t || (comment && strchr(comment, *t))) {
2044 return t + 1; /* needs to be non-NULL, but value doesn't matter */
2046 if (quote && (q = strchr(quote, *t))) {
2049 while (*t && *t != *q)
2051 if (!*t || (t[1] && !strchr(del, t[1])))
2059 while (*t && !strchr(del, *t))
2065 /* Parses config with following syntax:
2068 * option-name = value
2070 * option-name value {
2071 * option-name [=] value
2075 void getgeneralconfig(FILE *f, char *block, ...) {
2078 /* initialise lots of stuff to avoid stupid compiler warnings */
2079 char *tokens[3], *s, *opt = NULL, *val = NULL, *word, *optval, **str = NULL;
2080 int type = 0, tcount, conftype = 0;
2081 void (*cbk)(FILE *, char *, char *, char *) = NULL;
2083 while (fgets(line, 1024, f)) {
2085 for (tcount = 0; tcount < 3; tcount++) {
2086 s = strtokenquote(s, &tokens[tcount], " \t\n", "\"'", tcount ? NULL : "#");
2088 debugx(1, DBG_ERR, "Syntax error in line starting with: %s", line);
2089 if (!tokens[tcount])
2092 if (!tcount || **tokens == '#')
2095 if (**tokens == '}') {
2098 debugx(1, DBG_ERR, "configuration error, found } with no matching {");
2105 conftype = CONF_STR;
2108 if (tokens[1][0] == '=' && tokens[1][1] == '\0') {
2111 conftype = CONF_STR;
2114 if (tokens[2][0] == '{' && tokens[2][1] == '\0') {
2117 conftype = CONF_CBK;
2123 debugx(1, DBG_ERR, "configuration error in block %s, line starting with %s", block, tokens[0]);
2124 debugx(1, DBG_ERR, "configuration error, syntax error in line starting with %s", tokens[0]);
2128 debugx(1, DBG_ERR, "configuration error, option %s needs a non-empty value", opt);
2130 va_start(ap, block);
2131 while ((word = va_arg(ap, char *))) {
2132 type = va_arg(ap, int);
2135 str = va_arg(ap, char **);
2137 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2140 cbk = va_arg(ap, void (*)(FILE *, char *, char *, char *));
2143 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2145 if (!strcasecmp(opt, word))
2152 debugx(1, DBG_ERR, "configuration error in block %s, unknown option %s", block, opt);
2153 debugx(1, DBG_ERR, "configuration error, unknown option %s", opt);
2156 if (type != conftype) {
2158 debugx(1, DBG_ERR, "configuration error in block %s, wrong syntax for option %s", block, opt);
2159 debugx(1, DBG_ERR, "configuration error, wrong syntax for option %s", opt);
2165 debug(DBG_DBG, "getgeneralconfig: block %s: %s = %s", block, opt, val);
2167 debug(DBG_DBG, "getgeneralconfig: %s = %s", opt, val);
2168 *str = stringcopy(val, 0);
2171 optval = malloc(strlen(opt) + strlen(val) + 2);
2173 debugx(1, DBG_ERR, "malloc failed");
2174 sprintf(optval, "%s %s", opt, val);
2175 cbk(f, optval, opt, val);
2179 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2184 int addmatchcertattr(struct clsrvconf *conf, char *matchcertattr) {
2187 v = matchcertattr + 20;
2188 if (strncasecmp(matchcertattr, "SubjectAltName:URI:/", 20) || !*v)
2190 /* regexp, remove optional trailing / if present */
2191 if (v[strlen(v) - 1] == '/')
2192 v[strlen(v) - 1] = '\0';
2196 conf->certuriregex = malloc(sizeof(regex_t));
2197 if (!conf->certuriregex) {
2198 debug(DBG_ERR, "malloc failed");
2201 if (regcomp(conf->certuriregex, v, REG_ICASE | REG_NOSUB)) {
2202 regfree(conf->certuriregex);
2203 conf->certuriregex = NULL;
2204 debug(DBG_ERR, "failed to compile regular expression %s", v);
2210 void confclient_cb(FILE *f, char *block, char *opt, char *val) {
2211 char *type = NULL, *tls = NULL, *matchcertattr = NULL;
2212 struct clsrvconf *conf;
2214 debug(DBG_DBG, "confclient_cb called for %s", block);
2216 conf = malloc(sizeof(struct clsrvconf));
2217 if (!conf || !list_push(clconfs, conf))
2218 debugx(1, DBG_ERR, "malloc failed");
2219 memset(conf, 0, sizeof(struct clsrvconf));
2221 getgeneralconfig(f, block,
2222 "type", CONF_STR, &type,
2223 "host", CONF_STR, &conf->host,
2224 "secret", CONF_STR, &conf->secret,
2225 "tls", CONF_STR, &tls,
2226 "matchcertificateattribute", CONF_STR, &matchcertattr,
2230 /* leave conf->name to be NULL for clients */
2232 conf->host = stringcopy(val, 0);
2234 if (type && !strcasecmp(type, "udp")) {
2237 } else if (type && !strcasecmp(type, "tls")) {
2238 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultclient", "default");
2240 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2241 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2242 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2246 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2251 free(matchcertattr);
2253 if (!resolvepeer(conf, 0))
2254 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2256 if (!conf->secret) {
2257 if (conf->type == 'U')
2258 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2259 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2263 void confserver_cb(FILE *f, char *block, char *opt, char *val) {
2264 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *statusserver = NULL;
2265 struct clsrvconf *conf;
2267 debug(DBG_DBG, "confserver_cb called for %s", block);
2269 conf = malloc(sizeof(struct clsrvconf));
2270 if (!conf || !list_push(srvconfs, conf))
2271 debugx(1, DBG_ERR, "malloc failed");
2272 memset(conf, 0, sizeof(struct clsrvconf));
2274 getgeneralconfig(f, block,
2275 "type", CONF_STR, &type,
2276 "host", CONF_STR, &conf->host,
2277 "port", CONF_STR, &conf->port,
2278 "secret", CONF_STR, &conf->secret,
2279 "tls", CONF_STR, &tls,
2280 "matchcertificateattribute", CONF_STR, &matchcertattr,
2281 "StatusServer", CONF_STR, &statusserver,
2285 conf->name = stringcopy(val, 0);
2287 conf->host = stringcopy(val, 0);
2289 if (type && !strcasecmp(type, "udp")) {
2293 conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
2294 } else if (type && !strcasecmp(type, "tls")) {
2295 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultserver", "default");
2297 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2298 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2299 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2301 conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
2305 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2310 free(matchcertattr);
2312 if (!resolvepeer(conf, 0))
2313 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2315 if (!conf->secret) {
2316 if (conf->type == 'U')
2317 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2318 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2322 if (!strcasecmp(statusserver, "on"))
2323 conf->statusserver = 1;
2324 else if (strcasecmp(statusserver, "off"))
2325 debugx(1, DBG_ERR, "error in block %s, StatusServer is %s, must be on or off", block, statusserver);
2330 void confrealm_cb(FILE *f, char *block, char *opt, char *val) {
2331 char *server = NULL, *msg = NULL;
2333 debug(DBG_DBG, "confrealm_cb called for %s", block);
2335 getgeneralconfig(f, block,
2336 "server", CONF_STR, &server,
2337 "ReplyMessage", CONF_STR, &msg,
2341 addrealm(val, server, msg);
2345 void conftls_cb(FILE *f, char *block, char *opt, char *val) {
2346 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
2348 debug(DBG_DBG, "conftls_cb called for %s", block);
2350 getgeneralconfig(f, block,
2351 "CACertificateFile", CONF_STR, &cacertfile,
2352 "CACertificatePath", CONF_STR, &cacertpath,
2353 "CertificateFile", CONF_STR, &certfile,
2354 "CertificateKeyFile", CONF_STR, &certkeyfile,
2355 "CertificateKeyPassword", CONF_STR, &certkeypwd,
2359 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
2367 void getmainconfig(const char *configfile) {
2369 char *loglevel = NULL;
2371 f = openconfigfile(configfile);
2372 memset(&options, 0, sizeof(options));
2374 clconfs = list_create();
2376 debugx(1, DBG_ERR, "malloc failed");
2378 srvconfs = list_create();
2380 debugx(1, DBG_ERR, "malloc failed");
2382 realms = list_create();
2384 debugx(1, DBG_ERR, "malloc failed");
2386 tlsconfs = list_create();
2388 debugx(1, DBG_ERR, "malloc failed");
2390 getgeneralconfig(f, NULL,
2391 "ListenUDP", CONF_STR, &options.listenudp,
2392 "ListenTCP", CONF_STR, &options.listentcp,
2393 "LogLevel", CONF_STR, &loglevel,
2394 "LogDestination", CONF_STR, &options.logdestination,
2395 "Client", CONF_CBK, confclient_cb,
2396 "Server", CONF_CBK, confserver_cb,
2397 "Realm", CONF_CBK, confrealm_cb,
2398 "TLS", CONF_CBK, conftls_cb,
2405 if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
2406 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
2407 options.loglevel = *loglevel - '0';
2412 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *loglevel, char **configfile) {
2415 while ((c = getopt(argc, argv, "c:d:fv")) != -1) {
2418 *configfile = optarg;
2421 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
2422 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
2423 *loglevel = *optarg - '0';
2429 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
2434 if (!(argc - optind))
2438 debug(DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -v ]", argv[0]);
2442 int main(int argc, char **argv) {
2443 pthread_t udpserverth;
2444 struct list_node *entry;
2445 uint8_t foreground = 0, loglevel = 0;
2446 char *configfile = NULL;
2448 debug_init("radsecproxy");
2449 debug_set_level(DEBUG_LEVEL);
2450 getargs(argc, argv, &foreground, &loglevel, &configfile);
2452 debug_set_level(loglevel);
2453 getmainconfig(configfile ? configfile : CONFIG_MAIN);
2455 options.loglevel = loglevel;
2456 else if (options.loglevel)
2457 debug_set_level(options.loglevel);
2459 options.logdestination = NULL;
2461 if (!options.logdestination)
2462 options.logdestination = "x-syslog:///";
2463 debug_set_destination(options.logdestination);
2466 if (!list_first(clconfs))
2467 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
2468 if (!list_first(srvconfs))
2469 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
2470 if (!list_first(realms))
2471 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
2473 if (!foreground && (daemon(0, 0) < 0))
2474 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
2476 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
2478 if (client_udp_count) {
2479 udp_server_listen = server_create('U');
2480 udp_server_replyq = newreplyq();
2481 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
2482 debugx(1, DBG_ERR, "pthread_create failed");
2485 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2486 addserver((struct clsrvconf *)entry->data);
2487 if (pthread_create(&((struct clsrvconf *)entry->data)->servers->clientth, NULL, clientwr,
2488 (void *)((struct clsrvconf *)entry->data)->servers))
2489 debugx(1, DBG_ERR, "pthread_create failed");
2492 if (client_tls_count) {
2493 tcp_server_listen = server_create('T');
2494 return tlslistener();
2497 /* just hang around doing nothing, anything to do here? */