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>
50 #include "radsecproxy.h"
52 static struct options options;
53 static struct client *clients = NULL;
54 static struct server *servers = NULL;
55 static struct realm *realms = NULL;
56 static struct tls *tlsconfs = NULL;
58 static int client_udp_count = 0;
59 static int client_tls_count = 0;
60 static int client_count = 0;
61 static int server_udp_count = 0;
62 static int server_tls_count = 0;
63 static int server_count = 0;
64 static int realm_count = 0;
65 static int tls_count = 0;
67 static struct peer *tcp_server_listen;
68 static struct peer *udp_server_listen;
69 static struct replyq udp_server_replyq;
70 static int udp_server_sock = -1;
71 static pthread_mutex_t *ssl_locks;
72 static long *ssl_lock_count;
76 /* callbacks for making OpenSSL thread safe */
77 unsigned long ssl_thread_id() {
78 return (unsigned long)pthread_self();
81 void ssl_locking_callback(int mode, int type, const char *file, int line) {
82 if (mode & CRYPTO_LOCK) {
83 pthread_mutex_lock(&ssl_locks[type]);
84 ssl_lock_count[type]++;
86 pthread_mutex_unlock(&ssl_locks[type]);
89 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
90 int pwdlen = strlen(userdata);
91 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
93 memcpy(buf, userdata, pwdlen);
97 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
102 err_cert = X509_STORE_CTX_get_current_cert(ctx);
103 err = X509_STORE_CTX_get_error(ctx);
104 depth = X509_STORE_CTX_get_error_depth(ctx);
106 if (depth > MAX_CERT_DEPTH) {
108 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
109 X509_STORE_CTX_set_error(ctx, err);
113 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
114 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
117 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
118 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
119 debug(DBG_WARN, "\tIssuer=%s", buf);
121 case X509_V_ERR_CERT_NOT_YET_VALID:
122 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
123 debug(DBG_WARN, "\tCertificate not yet valid");
125 case X509_V_ERR_CERT_HAS_EXPIRED:
126 debug(DBG_WARN, "Certificate has expired");
128 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
129 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
134 printf("certificate verify returns %d\n", ok);
139 int resolvepeer(struct peer *peer, int ai_flags) {
140 struct addrinfo hints, *addrinfo;
142 memset(&hints, 0, sizeof(hints));
143 hints.ai_socktype = (peer->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
144 hints.ai_family = AF_UNSPEC;
145 hints.ai_flags = ai_flags;
146 if (getaddrinfo(peer->host, peer->port, &hints, &addrinfo)) {
147 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", peer->host, peer->port);
152 freeaddrinfo(peer->addrinfo);
153 peer->addrinfo = addrinfo;
157 int connecttoserver(struct addrinfo *addrinfo) {
159 struct addrinfo *res;
162 for (res = addrinfo; res; res = res->ai_next) {
163 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
165 debug(DBG_WARN, "connecttoserver: socket failed");
168 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
170 debug(DBG_WARN, "connecttoserver: connect failed");
177 int bindtoaddr(struct addrinfo *addrinfo) {
179 struct addrinfo *res;
181 for (res = addrinfo; res; res = res->ai_next) {
182 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
184 debug(DBG_WARN, "bindtoaddr: socket failed");
187 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
188 if (!bind(s, res->ai_addr, res->ai_addrlen))
190 debug(DBG_WARN, "bindtoaddr: bind failed");
196 /* returns the client with matching address, or NULL */
197 /* if client argument is not NULL, we only check that one client */
198 struct client *find_client(char type, struct sockaddr *addr, struct client *client) {
199 struct sockaddr_in6 *sa6 = NULL;
200 struct in_addr *a4 = NULL;
203 struct addrinfo *res;
205 if (addr->sa_family == AF_INET6) {
206 sa6 = (struct sockaddr_in6 *)addr;
207 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
208 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
210 a4 = &((struct sockaddr_in *)addr)->sin_addr;
212 c = (client ? client : clients);
213 for (i = 0; i < client_count; i++) {
214 if (c->peer.type == type)
215 for (res = c->peer.addrinfo; res; res = res->ai_next)
216 if ((a4 && res->ai_family == AF_INET &&
217 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
218 (sa6 && res->ai_family == AF_INET6 &&
219 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
228 /* returns the server with matching address, or NULL */
229 /* if server argument is not NULL, we only check that one server */
230 struct server *find_server(char type, struct sockaddr *addr, struct server *server) {
231 struct sockaddr_in6 *sa6 = NULL;
232 struct in_addr *a4 = NULL;
235 struct addrinfo *res;
237 if (addr->sa_family == AF_INET6) {
238 sa6 = (struct sockaddr_in6 *)addr;
239 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
240 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
242 a4 = &((struct sockaddr_in *)addr)->sin_addr;
244 s = (server ? server : servers);
245 for (i = 0; i < server_count; i++) {
246 if (s->peer.type == type)
247 for (res = s->peer.addrinfo; res; res = res->ai_next)
248 if ((a4 && res->ai_family == AF_INET &&
249 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
250 (sa6 && res->ai_family == AF_INET6 &&
251 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
260 /* exactly one of client and server must be non-NULL */
261 /* if *peer == NULL we return who we received from, else require it to be from peer */
262 /* return from in sa if not NULL */
263 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
266 unsigned char buf[65536], *rad;
267 struct sockaddr_storage from;
268 socklen_t fromlen = sizeof(from);
271 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
273 debug(DBG_WARN, "radudpget: recv failed");
276 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
279 debug(DBG_WARN, "radudpget: packet too small");
285 debug(DBG_WARN, "radudpget: length too small");
290 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
294 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
297 ? (void *)find_client('U', (struct sockaddr *)&from, *client)
298 : (void *)find_server('U', (struct sockaddr *)&from, *server));
300 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer, ignoring");
307 debug(DBG_ERR, "radudpget: malloc failed");
309 memcpy(rad, buf, len);
311 *client = (struct client *)f; /* only need this if *client == NULL, but if not NULL *client == f here */
313 *server = (struct server *)f; /* only need this if *server == NULL, but if not NULL *server == f here */
319 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
320 int loc, i, l, n, r = 0;
323 STACK_OF(GENERAL_NAME) *alt;
326 debug(DBG_DBG, "subjectaltnameaddr");
328 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
332 ex = X509_get_ext(cert, loc);
333 alt = X509V3_EXT_d2i(ex);
337 n = sk_GENERAL_NAME_num(alt);
338 for (i = 0; i < n; i++) {
339 gn = sk_GENERAL_NAME_value(alt, i);
340 if (gn->type != GEN_IPADD)
343 v = (char *)ASN1_STRING_data(gn->d.ia5);
344 l = ASN1_STRING_length(gn->d.ia5);
345 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
346 && !memcmp(v, &addr, l)) {
351 GENERAL_NAMES_free(alt);
355 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
356 int loc, i, l, n, r = 0;
359 STACK_OF(GENERAL_NAME) *alt;
362 debug(DBG_DBG, "subjectaltnameregexp");
364 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
368 ex = X509_get_ext(cert, loc);
369 alt = X509V3_EXT_d2i(ex);
373 n = sk_GENERAL_NAME_num(alt);
374 for (i = 0; i < n; i++) {
375 gn = sk_GENERAL_NAME_value(alt, i);
376 if (gn->type != type)
379 v = (char *)ASN1_STRING_data(gn->d.ia5);
380 l = ASN1_STRING_length(gn->d.ia5);
384 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
387 if (memcmp(v, exact, l))
390 s = stringcopy((char *)v, l);
392 debug(DBG_ERR, "malloc failed");
395 if (regexec(regex, s, 0, NULL, 0)) {
404 GENERAL_NAMES_free(alt);
408 int tlsverifycert(struct peer *peer) {
415 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
417 struct in6_addr addr;
419 if (SSL_get_verify_result(peer->ssl) != X509_V_OK) {
420 debug(DBG_ERR, "tlsverifycert: basic validation failed");
421 while ((error = ERR_get_error()))
422 debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
426 cert = SSL_get_peer_certificate(peer->ssl);
428 debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
432 if (inet_pton(AF_INET, peer->host, &addr))
434 else if (inet_pton(AF_INET6, peer->host, &addr))
437 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, peer->host, NULL);
441 debug(DBG_DBG, "tlsverifycert: No subjectaltname matching %s %s", type ? "address" : "host", peer->host);
444 debug(DBG_DBG, "tlsverifycert: Found subjectaltname matching %s %s", type ? "address" : "host", peer->host);
446 nm = X509_get_subject_name(cert);
449 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
452 e = X509_NAME_get_entry(nm, loc);
453 s = X509_NAME_ENTRY_get_data(e);
454 v = (char *) ASN1_STRING_data(s);
455 l = ASN1_STRING_length(s);
459 printfchars(NULL, "cn", NULL, v, l);
461 if (l == strlen(peer->host) && !strncasecmp(peer->host, v, l)) {
463 debug(DBG_DBG, "tlsverifycert: Found cn matching host %s, All OK", peer->host);
469 debug(DBG_ERR, "tlsverifycert: cn not matching host %s", peer->host);
473 if (peer->certuriregex) {
474 r = subjectaltnameregexp(cert, GEN_URI, NULL, peer->certuriregex);
476 debug(DBG_DBG, "tlsverifycert: subjectaltname URI not matching regex");
480 debug(DBG_DBG, "tlsverifycert: subjectaltname URI matching regex");
486 void tlsconnect(struct server *server, struct timeval *when, char *text) {
490 debug(DBG_DBG, "tlsconnect called from %s", text);
491 pthread_mutex_lock(&server->lock);
492 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
493 /* already reconnected, nothing to do */
494 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
495 pthread_mutex_unlock(&server->lock);
499 debug(DBG_DBG, "tlsconnect %s", text);
502 gettimeofday(&now, NULL);
503 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
504 if (server->connectionok) {
505 server->connectionok = 0;
507 } else if (elapsed < 5)
509 else if (elapsed < 300) {
510 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
512 } else if (elapsed < 100000) {
513 debug(DBG_INFO, "tlsconnect: sleeping %ds", 600);
516 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
517 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->peer.host, server->peer.port);
518 if (server->sock >= 0)
520 if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0) {
521 debug(DBG_ERR, "tlsconnect: connecttoserver failed");
525 SSL_free(server->peer.ssl);
526 server->peer.ssl = SSL_new(server->peer.ssl_ctx);
527 SSL_set_fd(server->peer.ssl, server->sock);
528 if (SSL_connect(server->peer.ssl) > 0 && tlsverifycert(&server->peer))
531 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->peer.host, server->peer.port);
532 gettimeofday(&server->lastconnecttry, NULL);
533 pthread_mutex_unlock(&server->lock);
536 unsigned char *radtlsget(SSL *ssl) {
538 unsigned char buf[4], *rad;
541 for (total = 0; total < 4; total += cnt) {
542 cnt = SSL_read(ssl, buf + total, 4 - total);
544 debug(DBG_ERR, "radtlsget: connection lost");
545 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
546 /* remote end sent close_notify, send one back */
556 debug(DBG_ERR, "radtlsget: malloc failed");
561 for (; total < len; total += cnt) {
562 cnt = SSL_read(ssl, rad + total, len - total);
564 debug(DBG_ERR, "radtlsget: connection lost");
565 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
566 /* remote end sent close_notify, send one back */
578 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
581 debug(DBG_DBG, "radtlsget: got %d bytes", total);
585 int clientradput(struct server *server, unsigned char *rad) {
589 struct timeval lastconnecttry;
592 if (server->peer.type == 'U') {
593 if (send(server->sock, rad, len, 0) >= 0) {
594 debug(DBG_DBG, "clienradput: sent UDP of length %d to %s port %s", len, server->peer.host, server->peer.port);
597 debug(DBG_WARN, "clientradput: send failed");
601 lastconnecttry = server->lastconnecttry;
602 while ((cnt = SSL_write(server->peer.ssl, rad, len)) <= 0) {
603 while ((error = ERR_get_error()))
604 debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
605 tlsconnect(server, &lastconnecttry, "clientradput");
606 lastconnecttry = server->lastconnecttry;
609 server->connectionok = 1;
610 debug(DBG_DBG, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s",
611 cnt, len, server->peer.host);
615 int radsign(unsigned char *rad, unsigned char *sec) {
616 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
617 static unsigned char first = 1;
618 static EVP_MD_CTX mdctx;
622 pthread_mutex_lock(&lock);
624 EVP_MD_CTX_init(&mdctx);
628 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
629 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
630 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
631 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
633 pthread_mutex_unlock(&lock);
637 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
638 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
639 static unsigned char first = 1;
640 static EVP_MD_CTX mdctx;
641 unsigned char hash[EVP_MAX_MD_SIZE];
645 pthread_mutex_lock(&lock);
647 EVP_MD_CTX_init(&mdctx);
653 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
654 EVP_DigestUpdate(&mdctx, rad, 4) &&
655 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
656 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
657 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
658 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
660 !memcmp(hash, rad + 4, 16));
661 pthread_mutex_unlock(&lock);
665 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
666 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
667 static unsigned char first = 1;
668 static HMAC_CTX hmacctx;
670 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
672 pthread_mutex_lock(&lock);
674 HMAC_CTX_init(&hmacctx);
678 memcpy(auth, authattr, 16);
679 memset(authattr, 0, 16);
681 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
682 HMAC_Update(&hmacctx, rad, RADLEN(rad));
683 HMAC_Final(&hmacctx, hash, &md_len);
684 memcpy(authattr, auth, 16);
686 debug(DBG_WARN, "message auth computation failed");
687 pthread_mutex_unlock(&lock);
691 if (memcmp(auth, hash, 16)) {
692 debug(DBG_WARN, "message authenticator, wrong value");
693 pthread_mutex_unlock(&lock);
697 pthread_mutex_unlock(&lock);
701 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
702 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
703 static unsigned char first = 1;
704 static HMAC_CTX hmacctx;
710 pthread_mutex_lock(&lock);
712 HMAC_CTX_init(&hmacctx);
716 memset(authattrval, 0, 16);
718 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
719 HMAC_Update(&hmacctx, rad, RADLEN(rad));
720 HMAC_Final(&hmacctx, authattrval, &md_len);
722 debug(DBG_WARN, "message auth computation failed");
723 pthread_mutex_unlock(&lock);
727 pthread_mutex_unlock(&lock);
731 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
733 if (ATTRTYPE(attrs) == type)
735 length -= ATTRLEN(attrs);
736 attrs += ATTRLEN(attrs);
741 void sendrq(struct server *to, struct request *rq) {
745 pthread_mutex_lock(&to->newrq_mutex);
746 /* might simplify if only try nextid, might be ok */
747 for (i = to->nextid; i < MAX_REQUESTS; i++)
748 if (!to->requests[i].buf)
750 if (i == MAX_REQUESTS) {
751 for (i = 0; i < to->nextid; i++)
752 if (!to->requests[i].buf)
754 if (i == to->nextid) {
755 debug(DBG_WARN, "No room in queue, dropping request");
757 pthread_mutex_unlock(&to->newrq_mutex);
762 rq->buf[1] = (char)i;
764 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
765 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->peer.secret)) {
767 pthread_mutex_unlock(&to->newrq_mutex);
771 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->peer.host);
772 to->requests[i] = *rq;
777 debug(DBG_DBG, "signalling client writer");
778 pthread_cond_signal(&to->newrq_cond);
780 pthread_mutex_unlock(&to->newrq_mutex);
783 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
784 struct replyq *replyq = to->replyq;
786 if (!radsign(buf, (unsigned char *)to->peer.secret)) {
788 debug(DBG_WARN, "sendreply: failed to sign message");
792 pthread_mutex_lock(&replyq->count_mutex);
793 if (replyq->count == replyq->size) {
794 debug(DBG_WARN, "No room in queue, dropping request");
795 pthread_mutex_unlock(&replyq->count_mutex);
800 replyq->replies[replyq->count].buf = buf;
802 replyq->replies[replyq->count].tosa = *tosa;
805 if (replyq->count == 1) {
806 debug(DBG_DBG, "signalling server writer");
807 pthread_cond_signal(&replyq->count_cond);
809 pthread_mutex_unlock(&replyq->count_mutex);
812 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
813 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
814 static unsigned char first = 1;
815 static EVP_MD_CTX mdctx;
816 unsigned char hash[EVP_MAX_MD_SIZE], *input;
818 uint8_t i, offset = 0, out[128];
820 pthread_mutex_lock(&lock);
822 EVP_MD_CTX_init(&mdctx);
828 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
829 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
830 !EVP_DigestUpdate(&mdctx, input, 16) ||
831 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
833 pthread_mutex_unlock(&lock);
836 for (i = 0; i < 16; i++)
837 out[offset + i] = hash[i] ^ in[offset + i];
838 input = out + offset - 16;
843 memcpy(in, out, len);
844 pthread_mutex_unlock(&lock);
848 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
849 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
850 static unsigned char first = 1;
851 static EVP_MD_CTX mdctx;
852 unsigned char hash[EVP_MAX_MD_SIZE], *input;
854 uint8_t i, offset = 0, out[128];
856 pthread_mutex_lock(&lock);
858 EVP_MD_CTX_init(&mdctx);
864 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
865 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
866 !EVP_DigestUpdate(&mdctx, input, 16) ||
867 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
869 pthread_mutex_unlock(&lock);
872 for (i = 0; i < 16; i++)
873 out[offset + i] = hash[i] ^ in[offset + i];
879 memcpy(in, out, len);
880 pthread_mutex_unlock(&lock);
884 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
885 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
886 static unsigned char first = 1;
887 static EVP_MD_CTX mdctx;
888 unsigned char hash[EVP_MAX_MD_SIZE];
892 pthread_mutex_lock(&lock);
894 EVP_MD_CTX_init(&mdctx);
899 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
900 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
901 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
904 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
905 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
906 !EVP_DigestUpdate(&mdctx, auth, 16) ||
907 !EVP_DigestUpdate(&mdctx, salt, 2) ||
908 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
909 pthread_mutex_unlock(&lock);
914 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
917 for (i = 0; i < 16; i++)
920 for (offset = 16; offset < len; offset += 16) {
922 printf("text + offset - 16 c(%d): ", offset / 16);
923 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
925 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
926 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
927 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
928 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
930 pthread_mutex_unlock(&lock);
934 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
937 for (i = 0; i < 16; i++)
938 text[offset + i] ^= hash[i];
942 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
945 pthread_mutex_unlock(&lock);
949 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
950 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
951 static unsigned char first = 1;
952 static EVP_MD_CTX mdctx;
953 unsigned char hash[EVP_MAX_MD_SIZE];
958 pthread_mutex_lock(&lock);
960 EVP_MD_CTX_init(&mdctx);
965 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
966 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
967 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
970 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
971 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
972 !EVP_DigestUpdate(&mdctx, auth, 16) ||
973 !EVP_DigestUpdate(&mdctx, salt, 2) ||
974 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
975 pthread_mutex_unlock(&lock);
980 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
983 for (i = 0; i < 16; i++)
984 plain[i] = text[i] ^ hash[i];
986 for (offset = 16; offset < len; offset += 16) {
988 printf("text + offset - 16 c(%d): ", offset / 16);
989 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
991 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
992 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
993 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
994 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
996 pthread_mutex_unlock(&lock);
1000 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1003 for (i = 0; i < 16; i++)
1004 plain[offset + i] = text[offset + i] ^ hash[i];
1007 memcpy(text, plain, len);
1009 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1012 pthread_mutex_unlock(&lock);
1016 struct realm *id2realm(char *id, uint8_t len) {
1018 for (i = 0; i < realm_count; i++)
1019 if (!regexec(&realms[i].regex, id, 0, NULL, 0)) {
1020 debug(DBG_DBG, "found matching realm: %s", realms[i].name);
1026 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
1029 pthread_mutex_lock(&to->newrq_mutex);
1030 for (i = 0; i < MAX_REQUESTS; i++)
1031 if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
1033 pthread_mutex_unlock(&to->newrq_mutex);
1035 return i < MAX_REQUESTS;
1038 int attrvalidate(unsigned char *attrs, int length) {
1039 while (length > 1) {
1040 if (ATTRLEN(attrs) < 2) {
1041 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1044 length -= ATTRLEN(attrs);
1046 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1049 attrs += ATTRLEN(attrs);
1052 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1056 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1057 if (len < 16 || len > 128 || len % 16) {
1058 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1062 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1063 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1067 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1069 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1070 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1076 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1079 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1080 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1083 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1084 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1090 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1091 char *oldsecret, char *newsecret) {
1092 unsigned char *attr;
1094 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1095 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1096 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1102 void respondstatusserver(struct request *rq) {
1103 unsigned char *resp;
1107 debug(DBG_ERR, "respondstatusserver: malloc failed");
1110 memcpy(resp, rq->buf, 20);
1111 resp[0] = RAD_Access_Accept;
1114 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->peer.host);
1115 sendreply(rq->from, resp, rq->from->peer.type == 'U' ? &rq->fromsa : NULL);
1118 void respondreject(struct request *rq, char *message) {
1119 unsigned char *resp;
1123 len += 2 + strlen(message);
1127 debug(DBG_ERR, "respondreject: malloc failed");
1130 memcpy(resp, rq->buf, 20);
1131 resp[0] = RAD_Access_Reject;
1132 *(uint16_t *)(resp + 2) = htons(len);
1134 resp[20] = RAD_Attr_Reply_Message;
1135 resp[21] = len - 20;
1136 memcpy(resp + 22, message, len - 22);
1138 sendreply(rq->from, resp, rq->from->peer.type == 'U' ? &rq->fromsa : NULL);
1141 void radsrv(struct request *rq) {
1142 uint8_t code, id, *auth, *attrs, *attr;
1144 struct server *to = NULL;
1146 unsigned char *buf, newauth[16];
1147 struct realm *realm = NULL;
1150 code = *(uint8_t *)buf;
1151 id = *(uint8_t *)(buf + 1);
1153 auth = (uint8_t *)(buf + 4);
1155 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1157 if (code != RAD_Access_Request && code != RAD_Status_Server) {
1158 debug(DBG_INFO, "radsrv: server currently accepts only access-requests and status-server, ignoring");
1166 if (!attrvalidate(attrs, len)) {
1167 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1172 if (code == RAD_Access_Request) {
1173 attr = attrget(attrs, len, RAD_Attr_User_Name);
1175 debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1179 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1180 username[ATTRVALLEN(attr)] = '\0';
1181 debug(DBG_DBG, "Access Request with username: %s", username);
1183 realm = id2realm(username, strlen(username));
1185 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1189 to = servers + realm->serverno;
1191 if (to && rqinqueue(to, rq->from, id)) {
1192 debug(DBG_INFO, "radsrv: already got request from host %s with id %d, ignoring", rq->from->peer.host, id);
1198 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1199 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(buf, ATTRVAL(attr), rq->from->peer.secret))) {
1200 debug(DBG_WARN, "radsrv: message authentication failed");
1205 if (code == RAD_Status_Server) {
1206 respondstatusserver(rq);
1212 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->peer.host, username);
1213 respondreject(rq, realm->message);
1218 if (!RAND_bytes(newauth, 16)) {
1219 debug(DBG_WARN, "radsrv: failed to generate random auth");
1225 printfchars(NULL, "auth", "%02x ", auth, 16);
1228 attr = attrget(attrs, len, RAD_Attr_User_Password);
1230 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1231 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->peer.secret, to->peer.secret, auth, newauth)) {
1237 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1239 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1240 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->peer.secret, to->peer.secret, auth, newauth)) {
1247 memcpy(rq->origauth, auth, 16);
1248 memcpy(auth, newauth, 16);
1252 void *clientrd(void *arg) {
1253 struct server *server = (struct server *)arg;
1254 struct client *from;
1256 unsigned char *buf, *messageauth, *subattrs, *attrs, *attr;
1257 struct sockaddr_storage fromsa;
1258 struct timeval lastconnecttry;
1262 lastconnecttry = server->lastconnecttry;
1263 buf = (server->peer.type == 'U' ? radudpget(server->sock, NULL, &server, NULL) : radtlsget(server->peer.ssl));
1264 if (!buf && server->peer.type == 'T') {
1265 tlsconnect(server, &lastconnecttry, "clientrd");
1269 server->connectionok = 1;
1271 i = buf[1]; /* i is the id */
1274 case RAD_Access_Accept:
1275 debug(DBG_DBG, "got Access Accept with id %d", i);
1277 case RAD_Access_Reject:
1278 debug(DBG_DBG, "got Access Reject with id %d", i);
1280 case RAD_Access_Challenge:
1281 debug(DBG_DBG, "got Access Challenge with id %d", i);
1285 debug(DBG_INFO, "clientrd: discarding, only accept access accept, access reject and access challenge messages");
1289 pthread_mutex_lock(&server->newrq_mutex);
1290 if (!server->requests[i].buf || !server->requests[i].tries) {
1291 pthread_mutex_unlock(&server->newrq_mutex);
1293 debug(DBG_INFO, "clientrd: no matching request sent with this id, ignoring");
1297 if (server->requests[i].received) {
1298 pthread_mutex_unlock(&server->newrq_mutex);
1300 debug(DBG_INFO, "clientrd: already received, ignoring");
1304 if (!validauth(buf, server->requests[i].buf + 4, (unsigned char *)server->peer.secret)) {
1305 pthread_mutex_unlock(&server->newrq_mutex);
1307 debug(DBG_WARN, "clientrd: invalid auth, ignoring");
1311 from = server->requests[i].from;
1312 len = RADLEN(buf) - 20;
1315 if (!attrvalidate(attrs, len)) {
1316 pthread_mutex_unlock(&server->newrq_mutex);
1318 debug(DBG_WARN, "clientrd: attribute validation failed, ignoring packet");
1322 /* Message Authenticator */
1323 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1325 if (ATTRVALLEN(messageauth) != 16) {
1326 pthread_mutex_unlock(&server->newrq_mutex);
1328 debug(DBG_WARN, "clientrd: illegal message auth attribute length, ignoring packet");
1331 memcpy(tmp, buf + 4, 16);
1332 memcpy(buf + 4, server->requests[i].buf + 4, 16);
1333 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->peer.secret)) {
1334 pthread_mutex_unlock(&server->newrq_mutex);
1336 debug(DBG_WARN, "clientrd: message authentication failed");
1339 memcpy(buf + 4, tmp, 16);
1340 debug(DBG_DBG, "clientrd: message auth ok");
1343 if (*server->requests[i].buf == RAD_Status_Server) {
1344 server->requests[i].received = 1;
1345 pthread_mutex_unlock(&server->newrq_mutex);
1347 debug(DBG_INFO, "clientrd: got status server response from %s", server->peer.host);
1352 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1353 if (ATTRVALLEN(attr) <= 4)
1356 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
1359 sublen = ATTRVALLEN(attr) - 4;
1360 subattrs = ATTRVAL(attr) + 4;
1361 if (!attrvalidate(subattrs, sublen) ||
1362 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1363 server->requests + i, server->peer.secret, from->peer.secret) ||
1364 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1365 server->requests + i, server->peer.secret, from->peer.secret))
1369 pthread_mutex_unlock(&server->newrq_mutex);
1371 debug(DBG_WARN, "clientrd: MS attribute handling failed, ignoring packet");
1375 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject) {
1376 attr = attrget(server->requests[i].buf + 20, RADLEN(server->requests[i].buf) - 20, RAD_Attr_User_Name);
1377 /* we know the attribute exists */
1378 memcpy(tmp, ATTRVAL(attr), ATTRVALLEN(attr));
1379 tmp[ATTRVALLEN(attr)] = '\0';
1381 case RAD_Access_Accept:
1382 debug(DBG_INFO, "Access Accept for %s from %s", tmp, server->peer.host);
1384 case RAD_Access_Reject:
1385 debug(DBG_INFO, "Access Reject for %s from %s", tmp, server->peer.host);
1390 /* once we set received = 1, requests[i] may be reused */
1391 buf[1] = (char)server->requests[i].origid;
1392 memcpy(buf + 4, server->requests[i].origauth, 16);
1394 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1398 if (!createmessageauth(buf, ATTRVAL(messageauth), from->peer.secret)) {
1399 pthread_mutex_unlock(&server->newrq_mutex);
1403 debug(DBG_DBG, "clientrd: computed messageauthattr");
1406 if (from->peer.type == 'U')
1407 fromsa = server->requests[i].fromsa;
1408 server->requests[i].received = 1;
1409 pthread_mutex_unlock(&server->newrq_mutex);
1411 debug(DBG_DBG, "clientrd: giving packet back to where it came from");
1412 sendreply(from, buf, from->peer.type == 'U' ? &fromsa : NULL);
1416 void *clientwr(void *arg) {
1417 struct server *server = (struct server *)arg;
1419 pthread_t clientrdth;
1422 struct timeval now, lastsend;
1423 struct timespec timeout;
1424 struct request statsrvrq;
1425 unsigned char statsrvbuf[38];
1427 memset(&timeout, 0, sizeof(struct timespec));
1429 if (server->statusserver) {
1430 memset(&statsrvrq, 0, sizeof(struct request));
1431 memset(statsrvbuf, 0, sizeof(statsrvbuf));
1432 statsrvbuf[0] = RAD_Status_Server;
1434 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
1435 statsrvbuf[21] = 18;
1436 gettimeofday(&lastsend, NULL);
1439 if (server->peer.type == 'U') {
1440 if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0)
1441 debugx(1, DBG_ERR, "clientwr: connecttoserver failed");
1443 tlsconnect(server, NULL, "new client");
1445 if (pthread_create(&clientrdth, NULL, clientrd, (void *)server))
1446 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
1449 pthread_mutex_lock(&server->newrq_mutex);
1450 if (!server->newrq) {
1451 gettimeofday(&now, NULL);
1452 if (server->statusserver) {
1453 /* random 0-7 seconds */
1454 RAND_bytes(&rnd, 1);
1456 if (!timeout.tv_sec || timeout.tv_sec - now.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
1457 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
1459 if (timeout.tv_sec) {
1460 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1461 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1464 debug(DBG_DBG, "clientwr: waiting for new request");
1465 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1468 if (server->newrq) {
1469 debug(DBG_DBG, "clientwr: got new request");
1472 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1473 pthread_mutex_unlock(&server->newrq_mutex);
1475 for (i = 0; i < MAX_REQUESTS; i++) {
1476 pthread_mutex_lock(&server->newrq_mutex);
1477 while (i < MAX_REQUESTS && !server->requests[i].buf)
1479 if (i == MAX_REQUESTS) {
1480 pthread_mutex_unlock(&server->newrq_mutex);
1483 rq = server->requests + i;
1486 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
1488 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
1490 /* setting this to NULL means that it can be reused */
1493 pthread_mutex_unlock(&server->newrq_mutex);
1497 gettimeofday(&now, NULL);
1498 if (now.tv_sec < rq->expiry.tv_sec) {
1499 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1500 timeout.tv_sec = rq->expiry.tv_sec;
1501 pthread_mutex_unlock(&server->newrq_mutex);
1505 if (rq->tries == (*rq->buf == RAD_Status_Server || server->peer.type == 'T'
1506 ? 1 : REQUEST_RETRIES)) {
1507 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1508 if (*rq->buf == RAD_Status_Server)
1509 debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->peer.host);
1511 /* setting this to NULL means that it can be reused */
1513 pthread_mutex_unlock(&server->newrq_mutex);
1516 pthread_mutex_unlock(&server->newrq_mutex);
1518 rq->expiry.tv_sec = now.tv_sec +
1519 (*rq->buf == RAD_Status_Server || server->peer.type == 'T'
1520 ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
1521 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1522 timeout.tv_sec = rq->expiry.tv_sec;
1524 clientradput(server, server->requests[i].buf);
1525 gettimeofday(&lastsend, NULL);
1527 if (server->statusserver) {
1528 gettimeofday(&now, NULL);
1529 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
1530 if (!RAND_bytes(statsrvbuf + 4, 16)) {
1531 debug(DBG_WARN, "clientwr: failed to generate random auth");
1534 statsrvrq.buf = malloc(sizeof(statsrvbuf));
1535 if (!statsrvrq.buf) {
1536 debug(DBG_ERR, "clientwr: malloc failed");
1539 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
1540 debug(DBG_DBG, "clientwr: sending status server to %s", server->peer.host);
1541 lastsend.tv_sec = now.tv_sec;
1542 sendrq(server, &statsrvrq);
1548 void *udpserverwr(void *arg) {
1549 struct replyq *replyq = &udp_server_replyq;
1550 struct reply *reply = replyq->replies;
1552 pthread_mutex_lock(&replyq->count_mutex);
1554 while (!replyq->count) {
1555 debug(DBG_DBG, "udp server writer, waiting for signal");
1556 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1557 debug(DBG_DBG, "udp server writer, got signal");
1559 pthread_mutex_unlock(&replyq->count_mutex);
1561 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
1562 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
1563 debug(DBG_WARN, "sendudp: send failed");
1566 pthread_mutex_lock(&replyq->count_mutex);
1568 memmove(replyq->replies, replyq->replies + 1,
1569 replyq->count * sizeof(struct reply));
1573 void *udpserverrd(void *arg) {
1575 pthread_t udpserverwrth;
1577 if ((udp_server_sock = bindtoaddr(udp_server_listen->addrinfo)) < 0)
1578 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
1580 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
1581 udp_server_listen->host ? udp_server_listen->host : "*", udp_server_listen->port);
1583 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
1584 debugx(1, DBG_ERR, "pthread_create failed");
1587 memset(&rq, 0, sizeof(struct request));
1588 rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
1593 void *tlsserverwr(void *arg) {
1595 unsigned long error;
1596 struct client *client = (struct client *)arg;
1597 struct replyq *replyq;
1599 debug(DBG_DBG, "tlsserverwr starting for %s", client->peer.host);
1600 replyq = client->replyq;
1601 pthread_mutex_lock(&replyq->count_mutex);
1603 while (!replyq->count) {
1604 if (client->peer.ssl) {
1605 debug(DBG_DBG, "tls server writer, waiting for signal");
1606 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1607 debug(DBG_DBG, "tls server writer, got signal");
1609 if (!client->peer.ssl) {
1610 /* ssl might have changed while waiting */
1611 pthread_mutex_unlock(&replyq->count_mutex);
1612 debug(DBG_DBG, "tlsserverwr: exiting as requested");
1616 pthread_mutex_unlock(&replyq->count_mutex);
1617 cnt = SSL_write(client->peer.ssl, replyq->replies->buf, RADLEN(replyq->replies->buf));
1619 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
1620 cnt, RADLEN(replyq->replies->buf));
1622 while ((error = ERR_get_error()))
1623 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
1624 free(replyq->replies->buf);
1626 pthread_mutex_lock(&replyq->count_mutex);
1628 memmove(replyq->replies, replyq->replies + 1, replyq->count * sizeof(struct reply));
1632 void *tlsserverrd(void *arg) {
1634 unsigned long error;
1636 struct client *client = (struct client *)arg;
1637 pthread_t tlsserverwrth;
1640 debug(DBG_DBG, "tlsserverrd starting for %s", client->peer.host);
1641 ssl = client->peer.ssl;
1643 if (SSL_accept(ssl) <= 0) {
1644 while ((error = ERR_get_error()))
1645 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
1646 debug(DBG_ERR, "SSL_accept failed");
1649 if (tlsverifycert(&client->peer)) {
1650 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
1651 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
1655 memset(&rq, 0, sizeof(struct request));
1656 rq.buf = radtlsget(client->peer.ssl);
1659 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->peer.host);
1663 debug(DBG_ERR, "tlsserverrd: connection lost");
1664 /* stop writer by setting peer.ssl to NULL and give signal in case waiting for data */
1665 client->peer.ssl = NULL;
1666 pthread_mutex_lock(&client->replyq->count_mutex);
1667 pthread_cond_signal(&client->replyq->count_cond);
1668 pthread_mutex_unlock(&client->replyq->count_mutex);
1669 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
1670 pthread_join(tlsserverwrth, NULL);
1674 s = SSL_get_fd(ssl);
1676 shutdown(s, SHUT_RDWR);
1678 debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->peer.host);
1679 client->peer.ssl = NULL;
1684 pthread_t tlsserverth;
1686 struct sockaddr_storage from;
1687 size_t fromlen = sizeof(from);
1688 struct client *client;
1690 if ((s = bindtoaddr(tcp_server_listen->addrinfo)) < 0)
1691 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
1694 debug(DBG_WARN, "listening for incoming TCP on %s:%s",
1695 tcp_server_listen->host ? tcp_server_listen->host : "*", tcp_server_listen->port);
1698 snew = accept(s, (struct sockaddr *)&from, &fromlen);
1700 debug(DBG_WARN, "accept failed");
1703 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
1705 client = find_client('T', (struct sockaddr *)&from, NULL);
1707 debug(DBG_WARN, "ignoring request, not a known TLS client");
1708 shutdown(snew, SHUT_RDWR);
1713 if (client->peer.ssl) {
1714 debug(DBG_WARN, "Ignoring incoming TLS connection, already have one from this client");
1715 shutdown(snew, SHUT_RDWR);
1719 client->peer.ssl = SSL_new(client->peer.ssl_ctx);
1720 SSL_set_fd(client->peer.ssl, snew);
1721 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
1722 debug(DBG_ERR, "tlslistener: pthread_create failed");
1723 SSL_free(client->peer.ssl);
1724 shutdown(snew, SHUT_RDWR);
1726 client->peer.ssl = NULL;
1729 pthread_detach(tlsserverth);
1734 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
1738 unsigned long error;
1740 if (!certfile || !certkeyfile)
1741 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
1743 if (!cacertfile && !cacertpath)
1744 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
1747 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
1748 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
1749 for (i = 0; i < CRYPTO_num_locks(); i++) {
1750 ssl_lock_count[i] = 0;
1751 pthread_mutex_init(&ssl_locks[i], NULL);
1753 CRYPTO_set_id_callback(ssl_thread_id);
1754 CRYPTO_set_locking_callback(ssl_locking_callback);
1756 SSL_load_error_strings();
1759 while (!RAND_status()) {
1760 time_t t = time(NULL);
1761 pid_t pid = getpid();
1762 RAND_seed((unsigned char *)&t, sizeof(time_t));
1763 RAND_seed((unsigned char *)&pid, sizeof(pid));
1766 ctx = SSL_CTX_new(TLSv1_method());
1768 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
1769 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
1771 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
1772 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
1773 !SSL_CTX_check_private_key(ctx) ||
1774 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
1775 while ((error = ERR_get_error()))
1776 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
1777 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
1780 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
1781 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
1784 tlsconfs = realloc(tlsconfs, tls_count * sizeof(struct tls));
1786 debugx(1, DBG_ERR, "malloc failed");
1787 new = tlsconfs + tls_count - 1;
1788 memset(new, 0, sizeof(struct tls));
1789 new->name = stringcopy(value, 0);
1791 debugx(1, DBG_ERR, "malloc failed");
1794 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
1799 for (i = 0; i < tls_count; i++) {
1800 free(tlsconfs[i].name);
1801 if (!tlsconfs[i].count)
1802 SSL_CTX_free(tlsconfs[i].ctx);
1809 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
1810 int i, c1 = -1, c2 = -1;
1811 for (i = 0; i < tls_count; i++) {
1812 if (!strcasecmp(tlsconfs[i].name, alt1)) {
1816 if (c2 == -1 && alt2 && !strcasecmp(tlsconfs[i].name, alt2))
1820 i = (c1 == -1 ? c2 : c1);
1823 tlsconfs[i].count++;
1824 return tlsconfs[i].ctx;
1827 void addrealm(char *value, char *server, char *message) {
1829 struct realm *realm;
1830 char *s, *regex = NULL;
1833 for (i = 0; i < server_count; i++)
1834 if (!strcasecmp(server, servers[i].peer.host))
1836 if (i == server_count)
1837 debugx(1, DBG_ERR, "addrealm failed, no server %s", server);
1840 if (*value == '/') {
1841 /* regexp, remove optional trailing / if present */
1842 if (value[strlen(value) - 1] == '/')
1843 value[strlen(value) - 1] = '\0';
1845 /* not a regexp, let us make it one */
1846 if (*value == '*' && !value[1])
1847 regex = stringcopy(".*", 0);
1849 for (n = 0, s = value; *s;)
1852 regex = malloc(strlen(value) + n + 3);
1855 for (n = 1, s = value; *s; s++) {
1865 debugx(1, DBG_ERR, "malloc failed");
1866 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
1870 realms = realloc(realms, realm_count * sizeof(struct realm));
1872 debugx(1, DBG_ERR, "malloc failed");
1873 realm = realms + realm_count - 1;
1874 memset(realm, 0, sizeof(struct realm));
1875 realm->name = stringcopy(value, 0);
1877 debugx(1, DBG_ERR, "malloc failed");
1878 if (message && strlen(message) > 253)
1879 debugx(1, DBG_ERR, "ReplyMessage can be at most 253 bytes");
1880 realm->message = message;
1882 realm->serverno = i;
1883 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB))
1884 debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
1887 debug(DBG_DBG, "addrealm: added realm %s for server %s", value, server);
1890 char *parsehostport(char *s, struct peer *peer) {
1895 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
1899 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1901 debugx(1, DBG_ERR, "no ] matching initial [");
1905 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1908 debugx(1, DBG_ERR, "missing host/address");
1910 peer->host = stringcopy(field, p - field);
1913 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
1914 debugx(1, DBG_ERR, "unexpected character after ]");
1917 /* port number or service name is specified */;
1919 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1921 debugx(1, DBG_ERR, "syntax error, : but no following port");
1922 peer->port = stringcopy(field, p - field);
1924 peer->port = stringcopy(peer->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT, 0);
1928 FILE *openconfigfile(const char *filename) {
1930 char pathname[100], *base = NULL;
1932 f = fopen(filename, "r");
1934 debug(DBG_DBG, "reading config file %s", filename);
1938 if (strlen(filename) + 1 <= sizeof(pathname)) {
1939 /* basename() might modify the string */
1940 strcpy(pathname, filename);
1941 base = basename(pathname);
1942 f = fopen(base, "r");
1946 debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
1948 debug(DBG_DBG, "reading config file %s", base);
1952 struct peer *server_create(char type) {
1953 struct peer *server;
1956 server = malloc(sizeof(struct peer));
1958 debugx(1, DBG_ERR, "malloc failed");
1959 memset(server, 0, sizeof(struct peer));
1960 server->type = type;
1961 conf = (type == 'T' ? options.listentcp : options.listenudp);
1963 parsehostport(conf, server);
1964 if (!strcmp(server->host, "*")) {
1966 server->host = NULL;
1969 server->port = stringcopy(type == 'T' ? DEFAULT_TLS_PORT : DEFAULT_UDP_PORT, 0);
1970 if (!resolvepeer(server, AI_PASSIVE))
1971 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", server->host, server->port);
1975 /* returns NULL on error, where to continue parsing if token and ok. E.g. "" will return token with empty string */
1976 char *strtokenquote(char *s, char **token, char *del, char *quote, char *comment) {
1977 char *t = s, *q, *r;
1979 if (!t || !token || !del)
1981 while (*t && strchr(del, *t))
1983 if (!*t || (comment && strchr(comment, *t))) {
1985 return t + 1; /* needs to be non-NULL, but value doesn't matter */
1987 if (quote && (q = strchr(quote, *t))) {
1990 while (*t && *t != *q)
1992 if (!*t || (t[1] && !strchr(del, t[1])))
2000 while (*t && !strchr(del, *t))
2006 /* Parses config with following syntax:
2009 * option-name = value
2011 * option-name value {
2012 * option-name [=] value
2016 void getgeneralconfig(FILE *f, char *block, ...) {
2019 /* initialise lots of stuff to avoid stupid compiler warnings */
2020 char *tokens[3], *s, *opt = NULL, *val = NULL, *word, *optval, **str = NULL;
2021 int type = 0, tcount, conftype = 0;
2022 void (*cbk)(FILE *, char *, char *, char *) = NULL;
2024 while (fgets(line, 1024, f)) {
2026 for (tcount = 0; tcount < 3; tcount++) {
2027 s = strtokenquote(s, &tokens[tcount], " \t\r\n", "\"'", tcount ? NULL : "#");
2029 debugx(1, DBG_ERR, "Syntax error in line starting with: %s", line);
2030 if (!tokens[tcount])
2033 if (!tcount || **tokens == '#')
2036 if (**tokens == '}') {
2039 debugx(1, DBG_ERR, "configuration error, found } with no matching {");
2046 conftype = CONF_STR;
2049 if (tokens[1][0] == '=' && tokens[1][1] == '\0') {
2052 conftype = CONF_STR;
2055 if (tokens[2][0] == '{' && tokens[2][1] == '\0') {
2058 conftype = CONF_CBK;
2064 debugx(1, DBG_ERR, "configuration error in block %s, line starting with %s", block, tokens[0]);
2065 debugx(1, DBG_ERR, "configuration error, syntax error in line starting with %s", tokens[0]);
2069 debugx(1, DBG_ERR, "configuration error, option %s needs a non-empty value", opt);
2071 va_start(ap, block);
2072 while ((word = va_arg(ap, char *))) {
2073 type = va_arg(ap, int);
2076 str = va_arg(ap, char **);
2078 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2081 cbk = va_arg(ap, void (*)(FILE *, char *, char *, char *));
2084 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2086 if (!strcasecmp(opt, word))
2093 debugx(1, DBG_ERR, "configuration error in block %s, unknown option %s", block, opt);
2094 debugx(1, DBG_ERR, "configuration error, unknown option %s", opt);
2097 if (type != conftype) {
2099 debugx(1, DBG_ERR, "configuration error in block %s, wrong syntax for option %s", block, opt);
2100 debugx(1, DBG_ERR, "configuration error, wrong syntax for option %s", opt);
2106 debug(DBG_DBG, "getgeneralconfig: block %s: %s = %s", block, opt, val);
2108 debug(DBG_DBG, "getgeneralconfig: %s = %s", opt, val);
2110 debugx(1, DBG_ERR, "configuration error, option %s already set to %s", opt, *str);
2111 *str = stringcopy(val, 0);
2114 optval = malloc(strlen(opt) + strlen(val) + 2);
2116 debugx(1, DBG_ERR, "malloc failed");
2117 sprintf(optval, "%s %s", opt, val);
2118 cbk(f, optval, opt, val);
2122 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2127 int addmatchcertattr(struct peer *conf, char *matchcertattr) {
2130 v = matchcertattr + 20;
2131 if (strncasecmp(matchcertattr, "SubjectAltName:URI:/", 20) || !*v)
2133 /* regexp, remove optional trailing / if present */
2134 if (v[strlen(v) - 1] == '/')
2135 v[strlen(v) - 1] = '\0';
2139 conf->certuriregex = malloc(sizeof(regex_t));
2140 if (!conf->certuriregex) {
2141 debug(DBG_ERR, "malloc failed");
2144 if (regcomp(conf->certuriregex, v, REG_ICASE | REG_NOSUB)) {
2145 free(conf->certuriregex);
2146 conf->certuriregex = NULL;
2147 debug(DBG_ERR, "failed to compile regular expression %s", v);
2153 void confclsrv_cb(FILE *f, char *block, char *opt, char *val) {
2154 char *type = NULL, *secret = NULL, *port = NULL, *tls = NULL, *matchcertattr = NULL, *statusserver = NULL;
2155 struct client *client = NULL;
2156 struct server *server = NULL;
2159 debug(DBG_DBG, "confclsrv_cb called for %s", block);
2161 if (!strcasecmp(opt, "client")) {
2162 getgeneralconfig(f, block,
2163 "type", CONF_STR, &type,
2164 "secret", CONF_STR, &secret,
2165 "tls", CONF_STR, &tls,
2166 "matchcertificateattribute", CONF_STR, &matchcertattr,
2170 clients = realloc(clients, client_count * sizeof(struct client));
2172 debugx(1, DBG_ERR, "malloc failed");
2173 client = clients + client_count - 1;
2174 memset(client, 0, sizeof(struct client));
2175 peer = &client->peer;
2177 getgeneralconfig(f, block,
2178 "type", CONF_STR, &type,
2179 "secret", CONF_STR, &secret,
2180 "port", CONF_STR, &port,
2181 "tls", CONF_STR, &tls,
2182 "matchcertificateattribute", CONF_STR, &matchcertattr,
2183 "StatusServer", CONF_STR, &statusserver,
2187 servers = realloc(servers, server_count * sizeof(struct server));
2189 debugx(1, DBG_ERR, "malloc failed");
2190 server = servers + server_count - 1;
2191 memset(server, 0, sizeof(struct server));
2192 peer = &server->peer;
2195 if (!strcasecmp(statusserver, "on"))
2196 server->statusserver = 1;
2197 else if (strcasecmp(statusserver, "off"))
2198 debugx(1, DBG_ERR, "error in block %s, StatusServer is %s, must be on or off", block, statusserver);
2203 peer->host = stringcopy(val, 0);
2205 if (type && !strcasecmp(type, "udp")) {
2212 peer->port = stringcopy(DEFAULT_UDP_PORT, 0);
2214 } else if (type && !strcasecmp(type, "tls")) {
2216 peer->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultclient", "default");
2219 peer->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultserver", "default");
2222 peer->port = stringcopy(DEFAULT_TLS_PORT, 0);
2225 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2226 if (matchcertattr && !addmatchcertattr(peer, matchcertattr))
2227 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2230 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2235 free(matchcertattr);
2237 if (!resolvepeer(peer, 0))
2238 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", peer->host, peer->port);
2241 if (peer->type == 'U')
2242 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2243 peer->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2245 peer->secret = secret;
2249 if (peer->type == 'U')
2250 client->replyq = &udp_server_replyq;
2252 client->replyq = malloc(sizeof(struct replyq));
2253 if (!client->replyq)
2254 debugx(1, DBG_ERR, "malloc failed");
2255 client->replyq->replies = calloc(MAX_REQUESTS, sizeof(struct reply));
2256 if (!client->replyq->replies)
2257 debugx(1, DBG_ERR, "malloc failed");
2258 client->replyq->size = MAX_REQUESTS;
2259 client->replyq->count = 0;
2260 pthread_mutex_init(&client->replyq->count_mutex, NULL);
2261 pthread_cond_init(&client->replyq->count_cond, NULL);
2264 pthread_mutex_init(&server->lock, NULL);
2266 server->requests = calloc(MAX_REQUESTS, sizeof(struct request));
2267 if (!server->requests)
2268 debugx(1, DBG_ERR, "malloc failed");
2270 pthread_mutex_init(&server->newrq_mutex, NULL);
2271 pthread_cond_init(&server->newrq_cond, NULL);
2275 void confrealm_cb(FILE *f, char *block, char *opt, char *val) {
2276 char *server = NULL, *msg = NULL;
2278 debug(DBG_DBG, "confrealm_cb called for %s", block);
2280 getgeneralconfig(f, block,
2281 "server", CONF_STR, &server,
2282 "ReplyMessage", CONF_STR, &msg,
2286 addrealm(val, server, msg);
2290 void conftls_cb(FILE *f, char *block, char *opt, char *val) {
2291 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
2293 debug(DBG_DBG, "conftls_cb called for %s", block);
2295 getgeneralconfig(f, block,
2296 "CACertificateFile", CONF_STR, &cacertfile,
2297 "CACertificatePath", CONF_STR, &cacertpath,
2298 "CertificateFile", CONF_STR, &certfile,
2299 "CertificateKeyFile", CONF_STR, &certkeyfile,
2300 "CertificateKeyPassword", CONF_STR, &certkeypwd,
2304 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
2312 void getmainconfig(const char *configfile) {
2314 char *loglevel = NULL;
2316 f = openconfigfile(configfile);
2317 memset(&options, 0, sizeof(options));
2319 getgeneralconfig(f, NULL,
2320 "ListenUDP", CONF_STR, &options.listenudp,
2321 "ListenTCP", CONF_STR, &options.listentcp,
2322 "LogLevel", CONF_STR, &loglevel,
2323 "LogDestination", CONF_STR, &options.logdestination,
2324 "Client", CONF_CBK, confclsrv_cb,
2325 "Server", CONF_CBK, confclsrv_cb,
2326 "Realm", CONF_CBK, confrealm_cb,
2327 "TLS", CONF_CBK, conftls_cb,
2334 if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
2335 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
2336 options.loglevel = *loglevel - '0';
2340 if (client_udp_count) {
2341 udp_server_replyq.replies = malloc(client_udp_count * MAX_REQUESTS * sizeof(struct reply));
2342 if (!udp_server_replyq.replies)
2343 debugx(1, DBG_ERR, "malloc failed");
2344 udp_server_replyq.size = client_udp_count * MAX_REQUESTS;
2345 udp_server_replyq.count = 0;
2346 pthread_mutex_init(&udp_server_replyq.count_mutex, NULL);
2347 pthread_cond_init(&udp_server_replyq.count_cond, NULL);
2351 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *loglevel, char **configfile) {
2354 while ((c = getopt(argc, argv, "c:d:fv")) != -1) {
2357 *configfile = optarg;
2360 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
2361 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
2362 *loglevel = *optarg - '0';
2368 debugx(0, DBG_ERR, "radsecproxy 1.0p1");
2373 if (!(argc - optind))
2377 debug(DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -v ]", argv[0]);
2381 int main(int argc, char **argv) {
2382 pthread_t udpserverth;
2384 uint8_t foreground = 0, loglevel = 0;
2385 char *configfile = NULL;
2387 debug_init("radsecproxy");
2388 debug_set_level(DEBUG_LEVEL);
2389 getargs(argc, argv, &foreground, &loglevel, &configfile);
2391 debug_set_level(loglevel);
2392 getmainconfig(configfile ? configfile : CONFIG_MAIN);
2394 options.loglevel = loglevel;
2395 else if (options.loglevel)
2396 debug_set_level(options.loglevel);
2398 options.logdestination = NULL;
2400 if (!options.logdestination)
2401 options.logdestination = "x-syslog:///";
2402 debug_set_destination(options.logdestination);
2406 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
2408 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
2410 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
2412 if (!foreground && (daemon(0, 0) < 0))
2413 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
2415 debug(DBG_INFO, "radsecproxy 1.0p1 starting");
2417 if (client_udp_count) {
2418 udp_server_listen = server_create('U');
2419 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
2420 debugx(1, DBG_ERR, "pthread_create failed");
2423 for (i = 0; i < server_count; i++)
2424 if (pthread_create(&servers[i].clientth, NULL, clientwr, (void *)&servers[i]))
2425 debugx(1, DBG_ERR, "pthread_create failed");
2427 if (client_tls_count) {
2428 tcp_server_listen = server_create('T');
2429 return tlslistener();
2432 /* just hang around doing nothing, anything to do here? */