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 clsrvconf *udp_accserver_listen;
64 static struct replyq *udp_server_replyq = NULL;
65 static int udp_server_sock = -1;
66 static int udp_accserver_sock = -1;
67 static int udp_client4_sock = -1;
68 static int udp_client6_sock = -1;
69 static pthread_mutex_t *ssl_locks;
70 static long *ssl_lock_count;
74 /* callbacks for making OpenSSL thread safe */
75 unsigned long ssl_thread_id() {
76 return (unsigned long)pthread_self();
79 void ssl_locking_callback(int mode, int type, const char *file, int line) {
80 if (mode & CRYPTO_LOCK) {
81 pthread_mutex_lock(&ssl_locks[type]);
82 ssl_lock_count[type]++;
84 pthread_mutex_unlock(&ssl_locks[type]);
87 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
88 int pwdlen = strlen(userdata);
89 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
91 memcpy(buf, userdata, pwdlen);
95 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
100 err_cert = X509_STORE_CTX_get_current_cert(ctx);
101 err = X509_STORE_CTX_get_error(ctx);
102 depth = X509_STORE_CTX_get_error_depth(ctx);
104 if (depth > MAX_CERT_DEPTH) {
106 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
107 X509_STORE_CTX_set_error(ctx, err);
111 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
112 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
115 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
116 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
117 debug(DBG_WARN, "\tIssuer=%s", buf);
119 case X509_V_ERR_CERT_NOT_YET_VALID:
120 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
121 debug(DBG_WARN, "\tCertificate not yet valid");
123 case X509_V_ERR_CERT_HAS_EXPIRED:
124 debug(DBG_WARN, "Certificate has expired");
126 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
127 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
132 printf("certificate verify returns %d\n", ok);
137 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
138 struct addrinfo hints, *addrinfo;
142 slash = conf->host ? strchr(conf->host, '/') : NULL;
146 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
150 if (*s < '0' || *s > '9') {
151 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
154 plen = atoi(slash + 1);
155 if (plen < 0 || plen > 128) {
156 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
161 memset(&hints, 0, sizeof(hints));
162 hints.ai_socktype = (conf->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
163 hints.ai_family = AF_UNSPEC;
164 hints.ai_flags = ai_flags;
166 hints.ai_flags |= AI_NUMERICHOST;
167 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
168 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host, conf->port);
174 switch (addrinfo->ai_family) {
177 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
178 freeaddrinfo(addrinfo);
185 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
186 freeaddrinfo(addrinfo);
189 conf->prefixlen = plen;
191 conf->prefixlen = 255;
194 freeaddrinfo(conf->addrinfo);
195 conf->addrinfo = addrinfo;
199 int connecttoserver(struct addrinfo *addrinfo) {
201 struct addrinfo *res;
204 for (res = addrinfo; res; res = res->ai_next) {
205 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
207 debug(DBG_WARN, "connecttoserver: socket failed");
210 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
212 debug(DBG_WARN, "connecttoserver: connect failed");
219 int bindtoaddr(struct addrinfo *addrinfo) {
221 struct addrinfo *res;
223 for (res = addrinfo; res; res = res->ai_next) {
224 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
226 debug(DBG_WARN, "bindtoaddr: socket failed");
229 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
230 if (!bind(s, res->ai_addr, res->ai_addrlen))
232 debug(DBG_WARN, "bindtoaddr: bind failed");
238 /* returns 1 if the len first bits are equal, else 0 */
239 int prefixmatch(void *a1, void *a2, uint8_t len) {
240 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
242 if (l && memcmp(a1, a2, l))
247 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
250 /* returns the config with matching address, or NULL */
251 /* if conf argument is not NULL, we only check that one */
252 struct clsrvconf *find_conf(char type, struct sockaddr *addr, struct list *confs, struct clsrvconf *conf) {
253 struct sockaddr_in6 *sa6 = NULL;
254 struct in_addr *a4 = NULL;
255 struct addrinfo *res;
256 struct list_node *entry;
258 if (addr->sa_family == AF_INET6) {
259 sa6 = (struct sockaddr_in6 *)addr;
260 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
261 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
265 a4 = &((struct sockaddr_in *)addr)->sin_addr;
268 if (conf->type == type) {
269 if (conf->prefixlen == 255) {
270 for (res = conf->addrinfo; res; res = res->ai_next)
271 if ((a4 && res->ai_family == AF_INET &&
272 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
273 (sa6 && res->ai_family == AF_INET6 &&
274 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
277 res = conf->addrinfo;
279 ((a4 && res->ai_family == AF_INET &&
280 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
281 (sa6 && res->ai_family == AF_INET6 &&
282 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
289 for (entry = list_first(confs); entry; entry = list_next(entry)) {
290 conf = (struct clsrvconf *)entry->data;
291 if (conf->type == type) {
292 if (conf->prefixlen == 255) {
293 for (res = conf->addrinfo; res; res = res->ai_next)
294 if ((a4 && res->ai_family == AF_INET &&
295 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
296 (sa6 && res->ai_family == AF_INET6 &&
297 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
300 res = conf->addrinfo;
302 ((a4 && res->ai_family == AF_INET &&
303 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
304 (sa6 && res->ai_family == AF_INET6 &&
305 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
313 struct replyq *newreplyq() {
314 struct replyq *replyq;
316 replyq = malloc(sizeof(struct replyq));
318 debugx(1, DBG_ERR, "malloc failed");
319 replyq->replies = list_create();
320 if (!replyq->replies)
321 debugx(1, DBG_ERR, "malloc failed");
322 pthread_mutex_init(&replyq->mutex, NULL);
323 pthread_cond_init(&replyq->cond, NULL);
327 struct client *addclient(struct clsrvconf *conf) {
328 struct client *new = malloc(sizeof(struct client));
331 debug(DBG_ERR, "malloc failed");
334 if (!conf->clients) {
335 conf->clients = list_create();
336 if (!conf->clients) {
337 debug(DBG_ERR, "malloc failed");
342 memset(new, 0, sizeof(struct client));
344 new->replyq = conf->type == 'T' ? newreplyq() : udp_server_replyq;
346 list_push(conf->clients, new);
350 void removeclient(struct client *client) {
351 if (!client || !client->conf->clients)
354 list_removedata(client->conf->clients, client);
358 void addserver(struct clsrvconf *conf) {
362 debugx(1, DBG_ERR, "addserver: currently works with just one server per conf");
364 conf->servers = malloc(sizeof(struct server));
366 debugx(1, DBG_ERR, "malloc failed");
367 memset(conf->servers, 0, sizeof(struct server));
368 conf->servers->conf = conf;
370 if (conf->type == 'U') {
371 switch (conf->addrinfo->ai_family) {
373 if (udp_client4_sock < 0) {
374 struct sockaddr_in sa;
375 memset(&sa, 0, sizeof(sa));
376 sa.sin_family = AF_INET;
377 udp_client4_sock = socket(PF_INET, conf->addrinfo->ai_socktype, conf->addrinfo->ai_protocol);
378 if (udp_client4_sock < 0)
379 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
380 if (bind(udp_client4_sock, (struct sockaddr *)&sa, sizeof(sa)))
381 debugx(1, DBG_ERR, "addserver: failed to bind client socket for server %s", conf->host);
383 conf->servers->sock = udp_client4_sock;
386 if (udp_client6_sock < 0) {
387 struct sockaddr_in6 sa;
388 memset(&sa, 0, sizeof(sa));
389 sa.sin6_family = AF_INET6;
390 udp_client6_sock = socket(PF_INET6, conf->addrinfo->ai_socktype, conf->addrinfo->ai_protocol);
391 if (udp_client6_sock < 0)
392 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
394 setsockopt(udp_client6_sock, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&on, sizeof(on));
396 if (bind(udp_client6_sock, (struct sockaddr *)&sa, sizeof(sa)))
397 debugx(1, DBG_ERR, "addserver: failed to bind client socket for server %s", conf->host);
399 conf->servers->sock = udp_client6_sock;
402 debugx(1, DBG_ERR, "addserver: unsupported address family");
406 conf->servers->sock = -1;
408 pthread_mutex_init(&conf->servers->lock, NULL);
409 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
410 if (!conf->servers->requests)
411 debugx(1, DBG_ERR, "malloc failed");
412 conf->servers->newrq = 0;
413 pthread_mutex_init(&conf->servers->newrq_mutex, NULL);
414 pthread_cond_init(&conf->servers->newrq_cond, NULL);
417 /* exactly one of client and server must be non-NULL */
418 /* should probably take peer list (client(s) or server(s)) as argument instead */
419 /* if *peer == NULL we return who we received from, else require it to be from peer */
420 /* return from in sa if not NULL */
421 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
423 unsigned char buf[65536], *rad;
424 struct sockaddr_storage from;
425 socklen_t fromlen = sizeof(from);
427 struct list_node *node;
430 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
432 debug(DBG_WARN, "radudpget: recv failed");
435 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
438 debug(DBG_WARN, "radudpget: packet too small");
444 debug(DBG_WARN, "radudpget: length too small");
449 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
453 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
457 p = find_conf('U', (struct sockaddr *)&from, NULL, (*client)->conf);
459 p = find_conf('U', (struct sockaddr *)&from, clconfs, NULL);
462 p = find_conf('U', (struct sockaddr *)&from, NULL, (*server)->conf);
464 p = find_conf('U', (struct sockaddr *)&from, srvconfs, NULL);
467 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer, ignoring");
473 debug(DBG_ERR, "radudpget: malloc failed");
477 if (client && !*client) {
478 node = list_first(p->clients);
479 *client = node ? (struct client *)node->data : addclient(p);
484 } else if (server && !*server)
485 *server = p->servers;
489 memcpy(rad, buf, len);
495 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
496 int loc, i, l, n, r = 0;
499 STACK_OF(GENERAL_NAME) *alt;
502 debug(DBG_DBG, "subjectaltnameaddr");
504 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
508 ex = X509_get_ext(cert, loc);
509 alt = X509V3_EXT_d2i(ex);
513 n = sk_GENERAL_NAME_num(alt);
514 for (i = 0; i < n; i++) {
515 gn = sk_GENERAL_NAME_value(alt, i);
516 if (gn->type != GEN_IPADD)
519 v = (char *)ASN1_STRING_data(gn->d.ia5);
520 l = ASN1_STRING_length(gn->d.ia5);
521 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
522 && !memcmp(v, &addr, l)) {
527 GENERAL_NAMES_free(alt);
531 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
532 int loc, i, l, n, r = 0;
535 STACK_OF(GENERAL_NAME) *alt;
538 debug(DBG_DBG, "subjectaltnameregexp");
540 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
544 ex = X509_get_ext(cert, loc);
545 alt = X509V3_EXT_d2i(ex);
549 n = sk_GENERAL_NAME_num(alt);
550 for (i = 0; i < n; i++) {
551 gn = sk_GENERAL_NAME_value(alt, i);
552 if (gn->type != type)
555 v = (char *)ASN1_STRING_data(gn->d.ia5);
556 l = ASN1_STRING_length(gn->d.ia5);
560 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
563 if (memcmp(v, exact, l))
566 s = stringcopy((char *)v, l);
568 debug(DBG_ERR, "malloc failed");
571 if (regexec(regex, s, 0, NULL, 0)) {
580 GENERAL_NAMES_free(alt);
584 int tlsverifycert(SSL *ssl, struct clsrvconf *conf) {
591 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
593 struct in6_addr addr;
595 if (SSL_get_verify_result(ssl) != X509_V_OK) {
596 debug(DBG_ERR, "tlsverifycert: basic validation failed");
597 while ((error = ERR_get_error()))
598 debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
602 cert = SSL_get_peer_certificate(ssl);
604 debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
608 if (conf->prefixlen == 255) {
609 if (inet_pton(AF_INET, conf->host, &addr))
611 else if (inet_pton(AF_INET6, conf->host, &addr))
614 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
618 debug(DBG_DBG, "tlsverifycert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
621 debug(DBG_DBG, "tlsverifycert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
623 nm = X509_get_subject_name(cert);
626 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
629 e = X509_NAME_get_entry(nm, loc);
630 s = X509_NAME_ENTRY_get_data(e);
631 v = (char *) ASN1_STRING_data(s);
632 l = ASN1_STRING_length(s);
636 printfchars(NULL, "cn", NULL, v, l);
638 if (l == strlen(conf->host) && !strncasecmp(conf->host, v, l)) {
640 debug(DBG_DBG, "tlsverifycert: Found cn matching host %s", conf->host);
646 debug(DBG_ERR, "tlsverifycert: cn not matching host %s", conf->host);
651 if (conf->certuriregex) {
652 r = subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex);
654 debug(DBG_DBG, "tlsverifycert: subjectaltname URI not matching regex");
658 debug(DBG_DBG, "tlsverifycert: subjectaltname URI matching regex");
664 void tlsconnect(struct server *server, struct timeval *when, char *text) {
668 debug(DBG_DBG, "tlsconnect called from %s", text);
669 pthread_mutex_lock(&server->lock);
670 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
671 /* already reconnected, nothing to do */
672 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
673 pthread_mutex_unlock(&server->lock);
677 debug(DBG_DBG, "tlsconnect %s", text);
680 gettimeofday(&now, NULL);
681 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
682 if (server->connectionok) {
683 server->connectionok = 0;
685 } else if (elapsed < 5)
687 else if (elapsed < 300) {
688 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
690 } else if (elapsed < 100000) {
691 debug(DBG_INFO, "tlsconnect: sleeping %ds", 600);
694 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
695 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
696 if (server->sock >= 0)
698 if ((server->sock = connecttoserver(server->conf->addrinfo)) < 0) {
699 debug(DBG_ERR, "tlsconnect: connecttoserver failed");
703 SSL_free(server->ssl);
704 server->ssl = SSL_new(server->conf->ssl_ctx);
705 SSL_set_fd(server->ssl, server->sock);
706 if (SSL_connect(server->ssl) > 0 && tlsverifycert(server->ssl, server->conf))
709 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
710 gettimeofday(&server->lastconnecttry, NULL);
711 pthread_mutex_unlock(&server->lock);
714 unsigned char *radtlsget(SSL *ssl) {
716 unsigned char buf[4], *rad;
719 for (total = 0; total < 4; total += cnt) {
720 cnt = SSL_read(ssl, buf + total, 4 - total);
722 debug(DBG_ERR, "radtlsget: connection lost");
723 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
724 /* remote end sent close_notify, send one back */
734 debug(DBG_ERR, "radtlsget: malloc failed");
739 for (; total < len; total += cnt) {
740 cnt = SSL_read(ssl, rad + total, len - total);
742 debug(DBG_ERR, "radtlsget: connection lost");
743 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
744 /* remote end sent close_notify, send one back */
756 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
759 debug(DBG_DBG, "radtlsget: got %d bytes", total);
763 int clientradput(struct server *server, unsigned char *rad) {
767 struct timeval lastconnecttry;
768 struct clsrvconf *conf = server->conf;
771 if (conf->type == 'U') {
772 if (sendto(server->sock, rad, len, 0, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen) >= 0) {
773 debug(DBG_DBG, "clienradput: sent UDP of length %d to %s port %s", len, conf->host, conf->port);
776 debug(DBG_WARN, "clientradput: send failed");
780 lastconnecttry = server->lastconnecttry;
781 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
782 while ((error = ERR_get_error()))
783 debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
784 tlsconnect(server, &lastconnecttry, "clientradput");
785 lastconnecttry = server->lastconnecttry;
788 server->connectionok = 1;
789 debug(DBG_DBG, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
793 int radsign(unsigned char *rad, unsigned char *sec) {
794 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
795 static unsigned char first = 1;
796 static EVP_MD_CTX mdctx;
800 pthread_mutex_lock(&lock);
802 EVP_MD_CTX_init(&mdctx);
806 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
807 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
808 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
809 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
811 pthread_mutex_unlock(&lock);
815 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
816 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
817 static unsigned char first = 1;
818 static EVP_MD_CTX mdctx;
819 unsigned char hash[EVP_MAX_MD_SIZE];
823 pthread_mutex_lock(&lock);
825 EVP_MD_CTX_init(&mdctx);
831 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
832 EVP_DigestUpdate(&mdctx, rad, 4) &&
833 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
834 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
835 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
836 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
838 !memcmp(hash, rad + 4, 16));
839 pthread_mutex_unlock(&lock);
843 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
844 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
845 static unsigned char first = 1;
846 static HMAC_CTX hmacctx;
848 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
850 pthread_mutex_lock(&lock);
852 HMAC_CTX_init(&hmacctx);
856 memcpy(auth, authattr, 16);
857 memset(authattr, 0, 16);
859 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
860 HMAC_Update(&hmacctx, rad, RADLEN(rad));
861 HMAC_Final(&hmacctx, hash, &md_len);
862 memcpy(authattr, auth, 16);
864 debug(DBG_WARN, "message auth computation failed");
865 pthread_mutex_unlock(&lock);
869 if (memcmp(auth, hash, 16)) {
870 debug(DBG_WARN, "message authenticator, wrong value");
871 pthread_mutex_unlock(&lock);
875 pthread_mutex_unlock(&lock);
879 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
880 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
881 static unsigned char first = 1;
882 static HMAC_CTX hmacctx;
888 pthread_mutex_lock(&lock);
890 HMAC_CTX_init(&hmacctx);
894 memset(authattrval, 0, 16);
896 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
897 HMAC_Update(&hmacctx, rad, RADLEN(rad));
898 HMAC_Final(&hmacctx, authattrval, &md_len);
900 debug(DBG_WARN, "message auth computation failed");
901 pthread_mutex_unlock(&lock);
905 pthread_mutex_unlock(&lock);
909 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
911 if (ATTRTYPE(attrs) == type)
913 length -= ATTRLEN(attrs);
914 attrs += ATTRLEN(attrs);
919 void freerqdata(struct request *rq) {
920 if (rq->origusername)
921 free(rq->origusername);
926 void sendrq(struct server *to, struct request *rq) {
930 pthread_mutex_lock(&to->newrq_mutex);
931 /* might simplify if only try nextid, might be ok */
932 for (i = to->nextid; i < MAX_REQUESTS; i++)
933 if (!to->requests[i].buf)
935 if (i == MAX_REQUESTS) {
936 for (i = 0; i < to->nextid; i++)
937 if (!to->requests[i].buf)
939 if (i == to->nextid) {
940 debug(DBG_WARN, "No room in queue, dropping request");
942 pthread_mutex_unlock(&to->newrq_mutex);
947 rq->buf[1] = (char)i;
949 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
950 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
952 pthread_mutex_unlock(&to->newrq_mutex);
956 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
957 to->requests[i] = *rq;
962 debug(DBG_DBG, "signalling client writer");
963 pthread_cond_signal(&to->newrq_cond);
965 pthread_mutex_unlock(&to->newrq_mutex);
968 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
972 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
974 debug(DBG_WARN, "sendreply: failed to sign message");
978 reply = malloc(sizeof(struct reply));
981 debug(DBG_ERR, "sendreply: malloc failed");
984 memset(reply, 0, sizeof(struct reply));
989 pthread_mutex_lock(&to->replyq->mutex);
991 first = list_first(to->replyq->replies) == NULL;
993 if (!list_push(to->replyq->replies, reply)) {
994 pthread_mutex_unlock(&to->replyq->mutex);
997 debug(DBG_ERR, "sendreply: malloc failed");
1002 debug(DBG_DBG, "signalling server writer");
1003 pthread_cond_signal(&to->replyq->cond);
1005 pthread_mutex_unlock(&to->replyq->mutex);
1008 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1009 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1010 static unsigned char first = 1;
1011 static EVP_MD_CTX mdctx;
1012 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1013 unsigned int md_len;
1014 uint8_t i, offset = 0, out[128];
1016 pthread_mutex_lock(&lock);
1018 EVP_MD_CTX_init(&mdctx);
1024 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1025 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1026 !EVP_DigestUpdate(&mdctx, input, 16) ||
1027 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1029 pthread_mutex_unlock(&lock);
1032 for (i = 0; i < 16; i++)
1033 out[offset + i] = hash[i] ^ in[offset + i];
1034 input = out + offset - 16;
1039 memcpy(in, out, len);
1040 pthread_mutex_unlock(&lock);
1044 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1045 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1046 static unsigned char first = 1;
1047 static EVP_MD_CTX mdctx;
1048 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1049 unsigned int md_len;
1050 uint8_t i, offset = 0, out[128];
1052 pthread_mutex_lock(&lock);
1054 EVP_MD_CTX_init(&mdctx);
1060 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1061 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1062 !EVP_DigestUpdate(&mdctx, input, 16) ||
1063 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1065 pthread_mutex_unlock(&lock);
1068 for (i = 0; i < 16; i++)
1069 out[offset + i] = hash[i] ^ in[offset + i];
1070 input = in + offset;
1075 memcpy(in, out, len);
1076 pthread_mutex_unlock(&lock);
1080 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1081 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1082 static unsigned char first = 1;
1083 static EVP_MD_CTX mdctx;
1084 unsigned char hash[EVP_MAX_MD_SIZE];
1085 unsigned int md_len;
1088 pthread_mutex_lock(&lock);
1090 EVP_MD_CTX_init(&mdctx);
1095 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1096 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1097 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1100 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1101 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1102 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1103 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1104 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1105 pthread_mutex_unlock(&lock);
1110 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1113 for (i = 0; i < 16; i++)
1116 for (offset = 16; offset < len; offset += 16) {
1118 printf("text + offset - 16 c(%d): ", offset / 16);
1119 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1121 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1122 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1123 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1124 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1126 pthread_mutex_unlock(&lock);
1130 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1133 for (i = 0; i < 16; i++)
1134 text[offset + i] ^= hash[i];
1138 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1141 pthread_mutex_unlock(&lock);
1145 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1146 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1147 static unsigned char first = 1;
1148 static EVP_MD_CTX mdctx;
1149 unsigned char hash[EVP_MAX_MD_SIZE];
1150 unsigned int md_len;
1154 pthread_mutex_lock(&lock);
1156 EVP_MD_CTX_init(&mdctx);
1161 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1162 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1163 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1166 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1167 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1168 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1169 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1170 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1171 pthread_mutex_unlock(&lock);
1176 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1179 for (i = 0; i < 16; i++)
1180 plain[i] = text[i] ^ hash[i];
1182 for (offset = 16; offset < len; offset += 16) {
1184 printf("text + offset - 16 c(%d): ", offset / 16);
1185 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1187 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1188 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1189 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1190 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1192 pthread_mutex_unlock(&lock);
1196 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1199 for (i = 0; i < 16; i++)
1200 plain[offset + i] = text[offset + i] ^ hash[i];
1203 memcpy(text, plain, len);
1205 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1208 pthread_mutex_unlock(&lock);
1212 struct realm *id2realm(char *id, uint8_t len) {
1213 struct list_node *entry;
1214 struct realm *realm;
1216 for (entry = list_first(realms); entry; entry = list_next(entry)) {
1217 realm = (struct realm *)entry->data;
1218 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1219 debug(DBG_DBG, "found matching realm: %s", realm->name);
1226 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
1229 pthread_mutex_lock(&to->newrq_mutex);
1230 for (i = 0; i < MAX_REQUESTS; i++)
1231 if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
1233 pthread_mutex_unlock(&to->newrq_mutex);
1235 return i < MAX_REQUESTS;
1238 int attrvalidate(unsigned char *attrs, int length) {
1239 while (length > 1) {
1240 if (ATTRLEN(attrs) < 2) {
1241 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1244 length -= ATTRLEN(attrs);
1246 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1249 attrs += ATTRLEN(attrs);
1252 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1256 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1257 if (len < 16 || len > 128 || len % 16) {
1258 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1262 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1263 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1267 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1269 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1270 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1276 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1279 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1280 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1283 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1284 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1290 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1291 char *oldsecret, char *newsecret) {
1292 unsigned char *attr;
1294 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1295 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1296 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1302 /* returns a pointer to the resized attribute value */
1303 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1304 uint8_t *attrs, *attr, vallen;
1308 len = RADLEN(*buf) - 20;
1311 attr = attrget(attrs, len, type);
1315 vallen = ATTRVALLEN(attr);
1316 if (vallen == newvallen)
1319 len += newvallen - vallen;
1320 if (newvallen > vallen) {
1321 new = realloc(*buf, len);
1323 debug(DBG_ERR, "resizeattr: malloc failed");
1332 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1333 attr[1] = newvallen + 2;
1334 ((uint16_t *)*buf)[1] = htons(len + 20);
1338 int rewriteusername(struct request *rq, char *in) {
1339 size_t nmatch = 10, reslen = 0, start = 0;
1340 regmatch_t pmatch[10], *pfield;
1342 unsigned char *result;
1343 char *out = rq->from->conf->rewriteattrreplacement;
1345 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1346 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1350 rq->origusername = stringcopy(in, 0);
1351 if (!rq->origusername)
1354 for (i = start; out[i]; i++) {
1355 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1356 pfield = &pmatch[out[i + 1] - '0'];
1357 if (pfield->rm_so >= 0) {
1358 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1364 reslen += i - start;
1366 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1372 for (i = start; out[i]; i++) {
1373 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1374 pfield = &pmatch[out[i + 1] - '0'];
1375 if (pfield->rm_so >= 0) {
1376 memcpy(result + reslen, out + start, i - start);
1377 reslen += i - start;
1378 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1379 reslen += pfield->rm_eo - pfield->rm_so;
1386 memcpy(result + reslen, out + start, i - start);
1387 reslen += i - start;
1388 memcpy(in, result, reslen);
1393 void acclog(unsigned char *attrs, int length, char *host) {
1394 unsigned char *attr;
1397 attr = attrget(attrs, length, RAD_Attr_User_Name);
1399 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1402 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1403 username[ATTRVALLEN(attr)] = '\0';
1404 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1407 void respondaccounting(struct request *rq) {
1408 unsigned char *resp;
1412 debug(DBG_ERR, "respondstatusserver: malloc failed");
1415 memcpy(resp, rq->buf, 20);
1416 resp[0] = RAD_Accounting_Response;
1419 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1420 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1423 void respondstatusserver(struct request *rq) {
1424 unsigned char *resp;
1428 debug(DBG_ERR, "respondstatusserver: malloc failed");
1431 memcpy(resp, rq->buf, 20);
1432 resp[0] = RAD_Access_Accept;
1435 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1436 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1439 void respondreject(struct request *rq, char *message) {
1440 unsigned char *resp;
1443 if (message && *message)
1444 len += 2 + strlen(message);
1448 debug(DBG_ERR, "respondreject: malloc failed");
1451 memcpy(resp, rq->buf, 20);
1452 resp[0] = RAD_Access_Reject;
1453 *(uint16_t *)(resp + 2) = htons(len);
1454 if (message && *message) {
1455 resp[20] = RAD_Attr_Reply_Message;
1456 resp[21] = len - 20;
1457 memcpy(resp + 22, message, len - 22);
1459 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1462 struct server *realm2server(struct realm *realm) {
1463 struct list_node *entry;
1464 struct server *server, *best = NULL;
1466 for (entry = list_first(realm->srvconfs); entry; entry = list_next(entry)) {
1467 server = ((struct clsrvconf *)entry->data)->servers;
1468 if (!server->connectionok)
1470 if (!server->loststatsrv)
1476 if (server->loststatsrv < best->loststatsrv)
1482 void radsrv(struct request *rq) {
1483 uint8_t code, id, *auth, *attrs, *attr;
1485 struct server *to = NULL;
1487 unsigned char newauth[16];
1488 struct realm *realm = NULL;
1490 code = *(uint8_t *)rq->buf;
1491 id = *(uint8_t *)(rq->buf + 1);
1492 len = RADLEN(rq->buf);
1493 auth = (uint8_t *)(rq->buf + 4);
1495 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1497 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1498 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1504 attrs = rq->buf + 20;
1506 if (!attrvalidate(attrs, len)) {
1507 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1512 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1513 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
1514 debug(DBG_WARN, "radsrv: message authentication failed");
1519 if (code != RAD_Access_Request) {
1521 case RAD_Accounting_Request:
1522 acclog(attrs, len, rq->from->conf->host);
1523 respondaccounting(rq);
1525 case RAD_Status_Server:
1526 respondstatusserver(rq);
1533 /* code == RAD_Access_Request */
1534 attr = attrget(attrs, len, RAD_Attr_User_Name);
1536 debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1540 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1541 username[ATTRVALLEN(attr)] = '\0';
1543 if (rq->from->conf->rewriteattrregex) {
1544 if (!rewriteusername(rq, username)) {
1545 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1549 len = RADLEN(rq->buf) - 20;
1550 auth = (uint8_t *)(rq->buf + 4);
1551 attrs = rq->buf + 20;
1554 if (rq->origusername)
1555 debug(DBG_DBG, "Access Request with username: %s (originally %s)", username, rq->origusername);
1557 debug(DBG_DBG, "Access Request with username: %s", username);
1559 realm = id2realm(username, strlen(username));
1561 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1566 to = realm2server(realm);
1567 if (to && rqinqueue(to, rq->from, id)) {
1568 debug(DBG_INFO, "radsrv: already got request from host %s with id %d, ignoring", rq->from->conf->host, id);
1574 if (realm->message) {
1575 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, username);
1576 respondreject(rq, realm->message);
1582 if (!RAND_bytes(newauth, 16)) {
1583 debug(DBG_WARN, "radsrv: failed to generate random auth");
1589 printfchars(NULL, "auth", "%02x ", auth, 16);
1592 attr = attrget(attrs, len, RAD_Attr_User_Password);
1594 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1595 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1601 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1603 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1604 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1611 memcpy(rq->origauth, auth, 16);
1612 memcpy(auth, newauth, 16);
1616 int replyh(struct server *server, unsigned char *buf) {
1617 struct client *from;
1620 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
1621 struct sockaddr_storage fromsa;
1624 server->connectionok = 1;
1625 server->loststatsrv = 0;
1627 i = buf[1]; /* i is the id */
1630 case RAD_Access_Accept:
1631 debug(DBG_DBG, "got Access Accept with id %d", i);
1633 case RAD_Access_Reject:
1634 debug(DBG_DBG, "got Access Reject with id %d", i);
1636 case RAD_Access_Challenge:
1637 debug(DBG_DBG, "got Access Challenge with id %d", i);
1640 debug(DBG_INFO, "replyh: discarding, only accept access accept, access reject and access challenge messages");
1644 rq = server->requests + i;
1646 pthread_mutex_lock(&server->newrq_mutex);
1647 if (!rq->buf || !rq->tries) {
1648 pthread_mutex_unlock(&server->newrq_mutex);
1649 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
1654 pthread_mutex_unlock(&server->newrq_mutex);
1655 debug(DBG_INFO, "replyh: already received, ignoring reply");
1659 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
1660 pthread_mutex_unlock(&server->newrq_mutex);
1661 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
1666 len = RADLEN(buf) - 20;
1669 if (!attrvalidate(attrs, len)) {
1670 pthread_mutex_unlock(&server->newrq_mutex);
1671 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
1675 /* Message Authenticator */
1676 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1678 if (ATTRVALLEN(messageauth) != 16) {
1679 pthread_mutex_unlock(&server->newrq_mutex);
1680 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
1683 memcpy(tmp, buf + 4, 16);
1684 memcpy(buf + 4, rq->buf + 4, 16);
1685 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
1686 pthread_mutex_unlock(&server->newrq_mutex);
1687 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
1690 memcpy(buf + 4, tmp, 16);
1691 debug(DBG_DBG, "replyh: message auth ok");
1694 if (*rq->buf == RAD_Status_Server) {
1696 pthread_mutex_unlock(&server->newrq_mutex);
1697 debug(DBG_INFO, "replyh: got status server response from %s", server->conf->host);
1702 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1703 if (ATTRVALLEN(attr) <= 4)
1706 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
1709 sublen = ATTRVALLEN(attr) - 4;
1710 subattrs = ATTRVAL(attr) + 4;
1711 if (!attrvalidate(subattrs, sublen) ||
1712 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1713 rq, server->conf->secret, from->conf->secret) ||
1714 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1715 rq, server->conf->secret, from->conf->secret))
1719 pthread_mutex_unlock(&server->newrq_mutex);
1720 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1724 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject) {
1725 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
1726 /* we know the attribute exists */
1727 memcpy(tmp, ATTRVAL(attr), ATTRVALLEN(attr));
1728 tmp[ATTRVALLEN(attr)] = '\0';
1730 case RAD_Access_Accept:
1731 if (rq->origusername)
1732 debug(DBG_INFO, "Access Accept for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1734 debug(DBG_INFO, "Access Accept for %s from %s", tmp, server->conf->host);
1736 case RAD_Access_Reject:
1737 if (rq->origusername)
1738 debug(DBG_INFO, "Access Reject for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1740 debug(DBG_INFO, "Access Reject for %s from %s", tmp, server->conf->host);
1745 buf[1] = (char)rq->origid;
1746 memcpy(buf + 4, rq->origauth, 16);
1748 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1751 if (rq->origusername) {
1752 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
1754 pthread_mutex_unlock(&server->newrq_mutex);
1755 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1758 memcpy(username, rq->origusername, strlen(rq->origusername));
1759 len = RADLEN(buf) - 20;
1762 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1766 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
1767 pthread_mutex_unlock(&server->newrq_mutex);
1768 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
1771 debug(DBG_DBG, "replyh: computed messageauthattr");
1774 if (from->conf->type == 'U')
1775 fromsa = rq->fromsa;
1776 /* once we set received = 1, rq may be reused */
1778 pthread_mutex_unlock(&server->newrq_mutex);
1780 debug(DBG_DBG, "replyh: giving packet back to where it came from");
1781 sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
1785 void *udpclientrd(void *arg) {
1786 struct server *server;
1788 int *s = (int *)arg;
1792 buf = radudpget(*s, NULL, &server, NULL);
1793 if (!replyh(server, buf))
1798 void *tlsclientrd(void *arg) {
1799 struct server *server = (struct server *)arg;
1801 struct timeval lastconnecttry;
1804 /* yes, lastconnecttry is really necessary */
1805 lastconnecttry = server->lastconnecttry;
1806 buf = radtlsget(server->ssl);
1808 tlsconnect(server, &lastconnecttry, "clientrd");
1812 if (!replyh(server, buf))
1817 void *clientwr(void *arg) {
1818 struct server *server = (struct server *)arg;
1820 pthread_t tlsclientrdth;
1823 struct timeval now, lastsend;
1824 struct timespec timeout;
1825 struct request statsrvrq;
1826 unsigned char statsrvbuf[38];
1828 memset(&timeout, 0, sizeof(struct timespec));
1830 if (server->conf->statusserver) {
1831 memset(&statsrvrq, 0, sizeof(struct request));
1832 memset(statsrvbuf, 0, sizeof(statsrvbuf));
1833 statsrvbuf[0] = RAD_Status_Server;
1835 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
1836 statsrvbuf[21] = 18;
1837 gettimeofday(&lastsend, NULL);
1840 if (server->conf->type == 'U') {
1841 server->connectionok = 1;
1843 tlsconnect(server, NULL, "new client");
1844 server->connectionok = 1;
1845 if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server))
1846 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
1850 pthread_mutex_lock(&server->newrq_mutex);
1851 if (!server->newrq) {
1852 gettimeofday(&now, NULL);
1853 if (server->conf->statusserver) {
1854 /* random 0-7 seconds */
1855 RAND_bytes(&rnd, 1);
1857 if (!timeout.tv_sec || timeout.tv_sec - now.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
1858 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
1860 if (timeout.tv_sec) {
1861 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1862 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1865 debug(DBG_DBG, "clientwr: waiting for new request");
1866 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1869 if (server->newrq) {
1870 debug(DBG_DBG, "clientwr: got new request");
1873 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1874 pthread_mutex_unlock(&server->newrq_mutex);
1876 for (i = 0; i < MAX_REQUESTS; i++) {
1877 pthread_mutex_lock(&server->newrq_mutex);
1878 while (i < MAX_REQUESTS && !server->requests[i].buf)
1880 if (i == MAX_REQUESTS) {
1881 pthread_mutex_unlock(&server->newrq_mutex);
1884 rq = server->requests + i;
1887 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
1889 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
1891 /* setting this to NULL means that it can be reused */
1894 pthread_mutex_unlock(&server->newrq_mutex);
1898 gettimeofday(&now, NULL);
1899 if (now.tv_sec < rq->expiry.tv_sec) {
1900 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1901 timeout.tv_sec = rq->expiry.tv_sec;
1902 pthread_mutex_unlock(&server->newrq_mutex);
1906 if (rq->tries == (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
1907 ? 1 : REQUEST_RETRIES)) {
1908 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1909 if (*rq->buf == RAD_Status_Server) {
1910 debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->conf->host);
1911 if (server->loststatsrv < 255)
1912 server->loststatsrv++;
1915 /* setting this to NULL means that it can be reused */
1917 pthread_mutex_unlock(&server->newrq_mutex);
1920 pthread_mutex_unlock(&server->newrq_mutex);
1922 rq->expiry.tv_sec = now.tv_sec +
1923 (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
1924 ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
1925 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1926 timeout.tv_sec = rq->expiry.tv_sec;
1928 clientradput(server, server->requests[i].buf);
1929 gettimeofday(&lastsend, NULL);
1931 if (server->conf->statusserver) {
1932 gettimeofday(&now, NULL);
1933 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
1934 if (!RAND_bytes(statsrvbuf + 4, 16)) {
1935 debug(DBG_WARN, "clientwr: failed to generate random auth");
1938 statsrvrq.buf = malloc(sizeof(statsrvbuf));
1939 if (!statsrvrq.buf) {
1940 debug(DBG_ERR, "clientwr: malloc failed");
1943 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
1944 debug(DBG_DBG, "clientwr: sending status server to %s", server->conf->host);
1945 lastsend.tv_sec = now.tv_sec;
1946 sendrq(server, &statsrvrq);
1952 void *udpserverwr(void *arg) {
1953 struct replyq *replyq = udp_server_replyq;
1954 struct reply *reply;
1957 pthread_mutex_lock(&replyq->mutex);
1958 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
1959 debug(DBG_DBG, "udp server writer, waiting for signal");
1960 pthread_cond_wait(&replyq->cond, &replyq->mutex);
1961 debug(DBG_DBG, "udp server writer, got signal");
1963 pthread_mutex_unlock(&replyq->mutex);
1965 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
1966 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
1967 debug(DBG_WARN, "sendudp: send failed");
1973 void *udpserverrd(void *arg) {
1975 pthread_t udpserverwrth;
1977 if ((udp_server_sock = bindtoaddr(udp_server_listen->addrinfo)) < 0)
1978 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
1980 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
1981 udp_server_listen->host ? udp_server_listen->host : "*", udp_server_listen->port);
1983 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
1984 debugx(1, DBG_ERR, "pthread_create failed");
1987 memset(&rq, 0, sizeof(struct request));
1988 rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
1993 void *udpaccserverrd(void *arg) {
1996 if ((udp_accserver_sock = bindtoaddr(udp_accserver_listen->addrinfo)) < 0)
1997 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
1999 debug(DBG_WARN, "udpaccserverrd: listening for UDP on %s:%s",
2000 udp_accserver_listen->host ? udp_accserver_listen->host : "*", udp_accserver_listen->port);
2003 memset(&rq, 0, sizeof(struct request));
2004 rq.buf = radudpget(udp_accserver_sock, &rq.from, NULL, &rq.fromsa);
2005 if (*(uint8_t *)rq.buf == RAD_Accounting_Request) {
2009 debug(DBG_INFO, "udpaccserverrd: got something other than accounting-request, ignoring");
2014 void *tlsserverwr(void *arg) {
2016 unsigned long error;
2017 struct client *client = (struct client *)arg;
2018 struct replyq *replyq;
2019 struct reply *reply;
2021 debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
2022 replyq = client->replyq;
2024 pthread_mutex_lock(&replyq->mutex);
2025 while (!list_first(replyq->replies)) {
2027 debug(DBG_DBG, "tls server writer, waiting for signal");
2028 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2029 debug(DBG_DBG, "tls server writer, got signal");
2032 /* ssl might have changed while waiting */
2033 pthread_mutex_unlock(&replyq->mutex);
2034 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2038 reply = (struct reply *)list_shift(replyq->replies);
2039 pthread_mutex_unlock(&replyq->mutex);
2040 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2042 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
2043 cnt, RADLEN(reply->buf));
2045 while ((error = ERR_get_error()))
2046 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2052 void *tlsserverrd(void *arg) {
2054 unsigned long error;
2056 struct client *client = (struct client *)arg;
2057 pthread_t tlsserverwrth;
2060 debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2063 if (SSL_accept(ssl) <= 0) {
2064 while ((error = ERR_get_error()))
2065 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2066 debug(DBG_ERR, "SSL_accept failed");
2069 if (tlsverifycert(client->ssl, client->conf)) {
2070 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2071 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2075 memset(&rq, 0, sizeof(struct request));
2076 rq.buf = radtlsget(client->ssl);
2079 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2083 debug(DBG_ERR, "tlsserverrd: connection lost");
2084 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2086 pthread_mutex_lock(&client->replyq->mutex);
2087 pthread_cond_signal(&client->replyq->cond);
2088 pthread_mutex_unlock(&client->replyq->mutex);
2089 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2090 pthread_join(tlsserverwrth, NULL);
2094 s = SSL_get_fd(ssl);
2096 shutdown(s, SHUT_RDWR);
2098 debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->conf->host);
2099 removeclient(client);
2104 pthread_t tlsserverth;
2106 struct sockaddr_storage from;
2107 size_t fromlen = sizeof(from);
2108 struct clsrvconf *conf;
2109 struct client *client;
2111 if ((s = bindtoaddr(tcp_server_listen->addrinfo)) < 0)
2112 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
2115 debug(DBG_WARN, "listening for incoming TCP on %s:%s",
2116 tcp_server_listen->host ? tcp_server_listen->host : "*", tcp_server_listen->port);
2119 snew = accept(s, (struct sockaddr *)&from, &fromlen);
2121 debug(DBG_WARN, "accept failed");
2124 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2126 conf = find_conf('T', (struct sockaddr *)&from, clconfs, NULL);
2128 debug(DBG_WARN, "ignoring request, not a known TLS client");
2129 shutdown(snew, SHUT_RDWR);
2134 client = addclient(conf);
2137 debug(DBG_WARN, "Failed to create new client instance");
2138 shutdown(snew, SHUT_RDWR);
2142 client->ssl = SSL_new(client->conf->ssl_ctx);
2143 SSL_set_fd(client->ssl, snew);
2144 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
2145 debug(DBG_ERR, "tlslistener: pthread_create failed");
2146 SSL_free(client->ssl);
2147 removeclient(client);
2148 shutdown(snew, SHUT_RDWR);
2152 pthread_detach(tlsserverth);
2157 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
2161 unsigned long error;
2163 if (!certfile || !certkeyfile)
2164 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2166 if (!cacertfile && !cacertpath)
2167 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2170 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2171 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2172 for (i = 0; i < CRYPTO_num_locks(); i++) {
2173 ssl_lock_count[i] = 0;
2174 pthread_mutex_init(&ssl_locks[i], NULL);
2176 CRYPTO_set_id_callback(ssl_thread_id);
2177 CRYPTO_set_locking_callback(ssl_locking_callback);
2179 SSL_load_error_strings();
2182 while (!RAND_status()) {
2183 time_t t = time(NULL);
2184 pid_t pid = getpid();
2185 RAND_seed((unsigned char *)&t, sizeof(time_t));
2186 RAND_seed((unsigned char *)&pid, sizeof(pid));
2189 ctx = SSL_CTX_new(TLSv1_method());
2191 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2192 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2194 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2195 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2196 !SSL_CTX_check_private_key(ctx) ||
2197 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2198 while ((error = ERR_get_error()))
2199 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2200 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2203 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2204 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2206 new = malloc(sizeof(struct tls));
2207 if (!new || !list_push(tlsconfs, new))
2208 debugx(1, DBG_ERR, "malloc failed");
2210 memset(new, 0, sizeof(struct tls));
2211 new->name = stringcopy(value, 0);
2213 debugx(1, DBG_ERR, "malloc failed");
2216 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2220 struct list_node *entry;
2223 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2224 t = (struct tls *)entry->data;
2228 SSL_CTX_free(t->ctx);
2230 list_destroy(tlsconfs);
2234 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2235 struct list_node *entry;
2236 struct tls *t, *t1 = NULL, *t2 = NULL;
2238 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2239 t = (struct tls *)entry->data;
2240 if (!strcasecmp(t->name, alt1)) {
2244 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2255 void addrealm(char *value, char **servers, char *message) {
2257 struct realm *realm;
2258 char *s, *regex = NULL;
2259 struct list_node *entry;
2260 struct clsrvconf *conf;
2262 if (*value == '/') {
2263 /* regexp, remove optional trailing / if present */
2264 if (value[strlen(value) - 1] == '/')
2265 value[strlen(value) - 1] = '\0';
2267 /* not a regexp, let us make it one */
2268 if (*value == '*' && !value[1])
2269 regex = stringcopy(".*", 0);
2271 for (n = 0, s = value; *s;)
2274 regex = malloc(strlen(value) + n + 3);
2277 for (n = 1, s = value; *s; s++) {
2287 debugx(1, DBG_ERR, "malloc failed");
2288 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2291 realm = malloc(sizeof(struct realm));
2293 debugx(1, DBG_ERR, "malloc failed");
2295 memset(realm, 0, sizeof(struct realm));
2296 realm->name = stringcopy(value, 0);
2298 debugx(1, DBG_ERR, "malloc failed");
2299 if (message && strlen(message) > 253)
2300 debugx(1, DBG_ERR, "ReplyMessage can be at most 253 bytes");
2301 realm->message = message;
2303 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB))
2304 debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2308 if (servers && *servers) {
2309 realm->srvconfs = list_create();
2310 if (!realm->srvconfs)
2311 debugx(1, DBG_ERR, "malloc failed");
2312 for (n = 0; servers[n]; n++) {
2313 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2314 conf = (struct clsrvconf *)entry->data;
2315 if (!strcasecmp(servers[n], conf->name))
2319 debugx(1, DBG_ERR, "addrealm failed, no server %s", servers[n]);
2320 if (!list_push(realm->srvconfs, conf))
2321 debugx(1, DBG_ERR, "malloc failed");
2322 debug(DBG_DBG, "addrealm: added server %s for realm %s", conf->name, value);
2325 realm->srvconfs = NULL;
2327 if (!list_push(realms, realm))
2328 debugx(1, DBG_ERR, "malloc failed");
2329 debug(DBG_DBG, "addrealm: added realm %s", value);
2332 char *parsehostport(char *s, struct clsrvconf *conf) {
2337 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
2341 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
2343 debugx(1, DBG_ERR, "no ] matching initial [");
2347 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
2350 debugx(1, DBG_ERR, "missing host/address");
2352 conf->host = stringcopy(field, p - field);
2355 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
2356 debugx(1, DBG_ERR, "unexpected character after ]");
2359 /* port number or service name is specified */;
2361 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
2363 debugx(1, DBG_ERR, "syntax error, : but no following port");
2364 conf->port = stringcopy(field, p - field);
2366 conf->port = stringcopy(conf->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT, 0);
2370 FILE *openconfigfile(const char *filename) {
2372 char pathname[100], *base = NULL;
2374 f = fopen(filename, "r");
2376 debug(DBG_DBG, "reading config file %s", filename);
2380 if (strlen(filename) + 1 <= sizeof(pathname)) {
2381 /* basename() might modify the string */
2382 strcpy(pathname, filename);
2383 base = basename(pathname);
2384 f = fopen(base, "r");
2388 debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
2390 debug(DBG_DBG, "reading config file %s", base);
2394 struct clsrvconf *server_create(char type, char *lconf) {
2395 struct clsrvconf *conf;
2397 conf = malloc(sizeof(struct clsrvconf));
2399 debugx(1, DBG_ERR, "malloc failed");
2400 memset(conf, 0, sizeof(struct clsrvconf));
2403 parsehostport(lconf, conf);
2404 if (!strcmp(conf->host, "*")) {
2409 conf->port = stringcopy(type == 'T' ? DEFAULT_TLS_PORT : DEFAULT_UDP_PORT, 0);
2410 if (!resolvepeer(conf, AI_PASSIVE))
2411 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2415 /* returns NULL on error, where to continue parsing if token and ok. E.g. "" will return token with empty string */
2416 char *strtokenquote(char *s, char **token, char *del, char *quote, char *comment) {
2417 char *t = s, *q, *r;
2419 if (!t || !token || !del)
2421 while (*t && strchr(del, *t))
2423 if (!*t || (comment && strchr(comment, *t))) {
2425 return t + 1; /* needs to be non-NULL, but value doesn't matter */
2427 if (quote && (q = strchr(quote, *t))) {
2430 while (*t && *t != *q)
2432 if (!*t || (t[1] && !strchr(del, t[1])))
2440 while (*t && !strchr(del, *t))
2446 /* Parses config with following syntax:
2449 * option-name = value
2451 * option-name value {
2452 * option-name [=] value
2456 void getgeneralconfig(FILE *f, char *block, ...) {
2459 /* initialise lots of stuff to avoid stupid compiler warnings */
2460 char *tokens[3], *s, *opt = NULL, *val = NULL, *word, *optval, **str = NULL, ***mstr = NULL;
2461 int type = 0, tcount, conftype = 0, n;
2462 void (*cbk)(FILE *, char *, char *, char *) = NULL;
2464 while (fgets(line, 1024, f)) {
2466 for (tcount = 0; tcount < 3; tcount++) {
2467 s = strtokenquote(s, &tokens[tcount], " \t\r\n", "\"'", tcount ? NULL : "#");
2469 debugx(1, DBG_ERR, "Syntax error in line starting with: %s", line);
2470 if (!tokens[tcount])
2473 if (!tcount || **tokens == '#')
2476 if (**tokens == '}') {
2479 debugx(1, DBG_ERR, "configuration error, found } with no matching {");
2486 conftype = CONF_STR;
2489 if (tokens[1][0] == '=' && tokens[1][1] == '\0') {
2492 conftype = CONF_STR;
2495 if (tokens[2][0] == '{' && tokens[2][1] == '\0') {
2498 conftype = CONF_CBK;
2504 debugx(1, DBG_ERR, "configuration error in block %s, line starting with %s", block, tokens[0]);
2505 debugx(1, DBG_ERR, "configuration error, syntax error in line starting with %s", tokens[0]);
2509 debugx(1, DBG_ERR, "configuration error, option %s needs a non-empty value", opt);
2511 va_start(ap, block);
2512 while ((word = va_arg(ap, char *))) {
2513 type = va_arg(ap, int);
2516 str = va_arg(ap, char **);
2518 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2521 mstr = va_arg(ap, char ***);
2523 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2526 cbk = va_arg(ap, void (*)(FILE *, char *, char *, char *));
2529 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2531 if (!strcasecmp(opt, word))
2538 debugx(1, DBG_ERR, "configuration error in block %s, unknown option %s", block, opt);
2539 debugx(1, DBG_ERR, "configuration error, unknown option %s", opt);
2542 if (((type == CONF_STR || type == CONF_MSTR) && conftype != CONF_STR) ||
2543 (type == CONF_CBK && conftype != CONF_CBK)) {
2545 debugx(1, DBG_ERR, "configuration error in block %s, wrong syntax for option %s", block, opt);
2546 debugx(1, DBG_ERR, "configuration error, wrong syntax for option %s", opt);
2552 debug(DBG_DBG, "getgeneralconfig: block %s: %s = %s", block, opt, val);
2554 debug(DBG_DBG, "getgeneralconfig: %s = %s", opt, val);
2556 debugx(1, DBG_ERR, "configuration error, option %s already set to %s", opt, *str);
2557 *str = stringcopy(val, 0);
2559 debugx(1, DBG_ERR, "malloc failed");
2563 debug(DBG_DBG, "getgeneralconfig: block %s: %s = %s", block, opt, val);
2565 debug(DBG_DBG, "getgeneralconfig: %s = %s", opt, val);
2567 for (n = 0; (*mstr)[n]; n++);
2570 *mstr = realloc(*mstr, sizeof(char *) * (n + 2));
2572 debugx(1, DBG_ERR, "malloc failed");
2573 (*mstr)[n] = stringcopy(val, 0);
2574 (*mstr)[n + 1] = NULL;
2577 optval = malloc(strlen(opt) + strlen(val) + 2);
2579 debugx(1, DBG_ERR, "malloc failed");
2580 sprintf(optval, "%s %s", opt, val);
2581 cbk(f, optval, opt, val);
2585 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2590 int addmatchcertattr(struct clsrvconf *conf, char *matchcertattr) {
2593 v = matchcertattr + 20;
2594 if (strncasecmp(matchcertattr, "SubjectAltName:URI:/", 20) || !*v)
2596 /* regexp, remove optional trailing / if present */
2597 if (v[strlen(v) - 1] == '/')
2598 v[strlen(v) - 1] = '\0';
2602 conf->certuriregex = malloc(sizeof(regex_t));
2603 if (!conf->certuriregex) {
2604 debug(DBG_ERR, "malloc failed");
2607 if (regcomp(conf->certuriregex, v, REG_ICASE | REG_NOSUB)) {
2608 free(conf->certuriregex);
2609 conf->certuriregex = NULL;
2610 debug(DBG_ERR, "failed to compile regular expression %s", v);
2616 int addrewriteattr(struct clsrvconf *conf, char *rewriteattr) {
2619 v = rewriteattr + 11;
2620 if (strncasecmp(rewriteattr, "User-Name:/", 11) || !*v)
2622 /* regexp, remove optional trailing / if present */
2623 if (v[strlen(v) - 1] == '/')
2624 v[strlen(v) - 1] = '\0';
2632 conf->rewriteattrregex = malloc(sizeof(regex_t));
2633 if (!conf->rewriteattrregex) {
2634 debug(DBG_ERR, "malloc failed");
2638 conf->rewriteattrreplacement = stringcopy(w, 0);
2639 if (!conf->rewriteattrreplacement) {
2640 free(conf->rewriteattrregex);
2641 conf->rewriteattrregex = NULL;
2645 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
2646 free(conf->rewriteattrregex);
2647 conf->rewriteattrregex = NULL;
2648 free(conf->rewriteattrreplacement);
2649 conf->rewriteattrreplacement = NULL;
2650 debug(DBG_ERR, "failed to compile regular expression %s", v);
2657 void confclient_cb(FILE *f, char *block, char *opt, char *val) {
2658 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *rewriteattr = NULL;
2659 struct clsrvconf *conf;
2661 debug(DBG_DBG, "confclient_cb called for %s", block);
2663 conf = malloc(sizeof(struct clsrvconf));
2664 if (!conf || !list_push(clconfs, conf))
2665 debugx(1, DBG_ERR, "malloc failed");
2666 memset(conf, 0, sizeof(struct clsrvconf));
2668 getgeneralconfig(f, block,
2669 "type", CONF_STR, &type,
2670 "host", CONF_STR, &conf->host,
2671 "secret", CONF_STR, &conf->secret,
2672 "tls", CONF_STR, &tls,
2673 "matchcertificateattribute", CONF_STR, &matchcertattr,
2674 "rewriteattribute", CONF_STR, &rewriteattr,
2678 /* leave conf->name to be NULL for clients */
2680 conf->host = stringcopy(val, 0);
2682 if (type && !strcasecmp(type, "udp")) {
2685 } else if (type && !strcasecmp(type, "tls")) {
2686 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultclient", "default");
2688 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2689 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2690 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2694 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2699 free(matchcertattr);
2702 if (!addrewriteattr(conf, rewriteattr))
2703 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2707 if (!resolvepeer(conf, 0))
2708 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2710 if (!conf->secret) {
2711 if (conf->type == 'U')
2712 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2713 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2717 void confserver_cb(FILE *f, char *block, char *opt, char *val) {
2718 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *statusserver = NULL;
2719 struct clsrvconf *conf;
2721 debug(DBG_DBG, "confserver_cb called for %s", block);
2723 conf = malloc(sizeof(struct clsrvconf));
2724 if (!conf || !list_push(srvconfs, conf))
2725 debugx(1, DBG_ERR, "malloc failed");
2726 memset(conf, 0, sizeof(struct clsrvconf));
2728 getgeneralconfig(f, block,
2729 "type", CONF_STR, &type,
2730 "host", CONF_STR, &conf->host,
2731 "port", CONF_STR, &conf->port,
2732 "secret", CONF_STR, &conf->secret,
2733 "tls", CONF_STR, &tls,
2734 "matchcertificateattribute", CONF_STR, &matchcertattr,
2735 "StatusServer", CONF_STR, &statusserver,
2739 conf->name = stringcopy(val, 0);
2741 conf->host = stringcopy(val, 0);
2743 if (type && !strcasecmp(type, "udp")) {
2747 conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
2748 } else if (type && !strcasecmp(type, "tls")) {
2749 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultserver", "default");
2751 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2752 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2753 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2755 conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
2759 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2764 free(matchcertattr);
2766 if (!resolvepeer(conf, 0))
2767 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2769 if (!conf->secret) {
2770 if (conf->type == 'U')
2771 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2772 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2776 if (!strcasecmp(statusserver, "on"))
2777 conf->statusserver = 1;
2778 else if (strcasecmp(statusserver, "off"))
2779 debugx(1, DBG_ERR, "error in block %s, StatusServer is %s, must be on or off", block, statusserver);
2784 void confrealm_cb(FILE *f, char *block, char *opt, char *val) {
2785 char **servers = NULL, *msg = NULL;
2787 debug(DBG_DBG, "confrealm_cb called for %s", block);
2789 getgeneralconfig(f, block,
2790 "server", CONF_MSTR, &servers,
2791 "ReplyMessage", CONF_STR, &msg,
2795 addrealm(val, servers, msg);
2799 void conftls_cb(FILE *f, char *block, char *opt, char *val) {
2800 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
2802 debug(DBG_DBG, "conftls_cb called for %s", block);
2804 getgeneralconfig(f, block,
2805 "CACertificateFile", CONF_STR, &cacertfile,
2806 "CACertificatePath", CONF_STR, &cacertpath,
2807 "CertificateFile", CONF_STR, &certfile,
2808 "CertificateKeyFile", CONF_STR, &certkeyfile,
2809 "CertificateKeyPassword", CONF_STR, &certkeypwd,
2813 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
2821 void getmainconfig(const char *configfile) {
2823 char *loglevel = NULL;
2825 f = openconfigfile(configfile);
2826 memset(&options, 0, sizeof(options));
2828 clconfs = list_create();
2830 debugx(1, DBG_ERR, "malloc failed");
2832 srvconfs = list_create();
2834 debugx(1, DBG_ERR, "malloc failed");
2836 realms = list_create();
2838 debugx(1, DBG_ERR, "malloc failed");
2840 tlsconfs = list_create();
2842 debugx(1, DBG_ERR, "malloc failed");
2844 getgeneralconfig(f, NULL,
2845 "ListenUDP", CONF_STR, &options.listenudp,
2846 "ListenTCP", CONF_STR, &options.listentcp,
2847 "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
2848 "LogLevel", CONF_STR, &loglevel,
2849 "LogDestination", CONF_STR, &options.logdestination,
2850 "Client", CONF_CBK, confclient_cb,
2851 "Server", CONF_CBK, confserver_cb,
2852 "Realm", CONF_CBK, confrealm_cb,
2853 "TLS", CONF_CBK, conftls_cb,
2860 if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
2861 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
2862 options.loglevel = *loglevel - '0';
2867 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *loglevel, char **configfile) {
2870 while ((c = getopt(argc, argv, "c:d:fv")) != -1) {
2873 *configfile = optarg;
2876 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
2877 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
2878 *loglevel = *optarg - '0';
2884 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
2889 if (!(argc - optind))
2893 debug(DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -v ]", argv[0]);
2897 int main(int argc, char **argv) {
2898 pthread_t udpserverth, udpaccserverth, udpclient4rdth, udpclient6rdth;
2899 struct list_node *entry;
2900 uint8_t foreground = 0, loglevel = 0;
2901 char *configfile = NULL;
2903 debug_init("radsecproxy");
2904 debug_set_level(DEBUG_LEVEL);
2905 getargs(argc, argv, &foreground, &loglevel, &configfile);
2907 debug_set_level(loglevel);
2908 getmainconfig(configfile ? configfile : CONFIG_MAIN);
2910 options.loglevel = loglevel;
2911 else if (options.loglevel)
2912 debug_set_level(options.loglevel);
2914 options.logdestination = NULL;
2916 if (!options.logdestination)
2917 options.logdestination = "x-syslog:///";
2918 debug_set_destination(options.logdestination);
2921 if (!list_first(clconfs))
2922 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
2923 if (!list_first(srvconfs))
2924 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
2925 if (!list_first(realms))
2926 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
2928 if (!foreground && (daemon(0, 0) < 0))
2929 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
2931 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
2933 if (client_udp_count) {
2934 udp_server_listen = server_create('U', options.listenudp);
2935 udp_server_replyq = newreplyq();
2936 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
2937 debugx(1, DBG_ERR, "pthread_create failed");
2938 if (options.listenaccudp) {
2939 udp_accserver_listen = server_create('U', options.listenaccudp);
2940 if (pthread_create(&udpaccserverth, NULL, udpaccserverrd, NULL))
2941 debugx(1, DBG_ERR, "pthread_create failed");
2945 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2946 addserver((struct clsrvconf *)entry->data);
2947 if (pthread_create(&((struct clsrvconf *)entry->data)->servers->clientth, NULL, clientwr,
2948 (void *)((struct clsrvconf *)entry->data)->servers))
2949 debugx(1, DBG_ERR, "pthread_create failed");
2952 if (udp_client4_sock >= 0)
2953 if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
2954 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
2955 if (udp_client6_sock >= 0)
2956 if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
2957 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
2959 if (client_tls_count) {
2960 tcp_server_listen = server_create('T', options.listentcp);
2961 return tlslistener();
2964 /* just hang around doing nothing, anything to do here? */