2 * Copyright (C) 2006-2008 Stig Venaas <venaas@uninett.no>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
9 /* 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
33 * TCP accounting not yet supported
34 * We are not removing client requests from dynamic servers, see removeclientrqs()
38 #include <sys/socket.h>
39 #include <netinet/in.h>
48 #include <sys/types.h>
49 #include <sys/select.h>
52 #include <arpa/inet.h>
56 #include <openssl/ssl.h>
57 #include <openssl/rand.h>
58 #include <openssl/err.h>
59 #include <openssl/md5.h>
60 #include <openssl/hmac.h>
61 #include <openssl/x509v3.h>
66 #include "radsecproxy.h"
69 static struct options options;
70 static struct list *clconfs, *srvconfs;
71 struct list *realms, *tlsconfs, *rewriteconfs;
73 static struct addrinfo *srcprotores[4] = { NULL, NULL, NULL, NULL };
75 static struct queue *udp_server_replyq = NULL;
76 static int udp_client4_sock = -1;
77 static int udp_client6_sock = -1;
78 static int dtls_client4_sock = -1;
79 static int dtls_client6_sock = -1;
80 static pthread_mutex_t tlsconfs_lock;
81 static pthread_mutex_t *ssl_locks = NULL;
82 static long *ssl_lock_count;
86 /* minimum required declarations to avoid reordering code */
87 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
88 int dynamicconfig(struct server *server);
89 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
90 void freerealm(struct realm *realm);
91 void freeclsrvconf(struct clsrvconf *conf);
92 void freerqdata(struct request *rq);
93 void *udpserverrd(void *arg);
94 void *tlslistener(void *arg);
95 void *tcplistener(void *arg);
96 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text);
97 int tcpconnect(struct server *server, struct timeval *when, int timeout, char *text);
98 void *udpclientrd(void *arg);
99 void *tlsclientrd(void *arg);
100 void *tcpclientrd(void *arg);
101 int clientradputudp(struct server *server, unsigned char *rad);
102 int clientradputtls(struct server *server, unsigned char *rad);
103 int clientradputtcp(struct server *server, unsigned char *rad);
104 X509 *verifytlscert(SSL *ssl);
105 int radsrv(struct request *rq);
107 static const struct protodefs protodefs[] = {
108 { "udp", /* UDP, assuming RAD_UDP defined as 0 */
109 NULL, /* secretdefault */
110 SOCK_DGRAM, /* socktype */
111 "1812", /* portdefault */
112 REQUEST_RETRY_COUNT, /* retrycountdefault */
113 10, /* retrycountmax */
114 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
115 60, /* retryintervalmax */
116 udpserverrd, /* listener */
117 &options.sourceudp, /* srcaddrport */
118 NULL, /* connecter */
119 udpclientrd, /* clientreader */
120 clientradputudp /* clientradput */
122 { "tls", /* TLS, assuming RAD_TLS defined as 1 */
123 "mysecret", /* secretdefault */
124 SOCK_STREAM, /* socktype */
125 "2083", /* portdefault */
126 0, /* retrycountdefault */
127 0, /* retrycountmax */
128 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
129 60, /* retryintervalmax */
130 tlslistener, /* listener */
131 &options.sourcetls, /* srcaddrport */
132 tlsconnect, /* connecter */
133 tlsclientrd, /* clientreader */
134 clientradputtls /* clientradput */
136 { "tcp", /* TCP, assuming RAD_TCP defined as 2 */
137 NULL, /* secretdefault */
138 SOCK_STREAM, /* socktype */
139 "1812", /* portdefault */
140 0, /* retrycountdefault */
141 0, /* retrycountmax */
142 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
143 60, /* retryintervalmax */
144 tcplistener, /* listener */
145 &options.sourcetcp, /* srcaddrport */
146 tcpconnect, /* connecter */
147 tcpclientrd, /* clientreader */
148 clientradputtcp /* clientradput */
150 { "dtls", /* DTLS, assuming RAD_DTLS defined as 3 */
151 "mysecret", /* secretdefault */
152 SOCK_DGRAM, /* socktype */
153 "2083", /* portdefault */
154 REQUEST_RETRY_COUNT, /* retrycountdefault */
155 10, /* retrycountmax */
156 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
157 60, /* retryintervalmax */
158 udpdtlsserverrd, /* listener */
159 &options.sourcedtls, /* srcaddrport */
160 dtlsconnect, /* connecter */
161 dtlsclientrd, /* clientreader */
162 clientradputdtls /* clientradput */
168 uint8_t protoname2int(const char *name) {
171 for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
175 /* callbacks for making OpenSSL thread safe */
176 unsigned long ssl_thread_id() {
177 return (unsigned long)pthread_self();
180 void ssl_locking_callback(int mode, int type, const char *file, int line) {
181 if (mode & CRYPTO_LOCK) {
182 pthread_mutex_lock(&ssl_locks[type]);
183 ssl_lock_count[type]++;
185 pthread_mutex_unlock(&ssl_locks[type]);
188 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
189 int pwdlen = strlen(userdata);
190 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
192 memcpy(buf, userdata, pwdlen);
196 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
201 err_cert = X509_STORE_CTX_get_current_cert(ctx);
202 err = X509_STORE_CTX_get_error(ctx);
203 depth = X509_STORE_CTX_get_error_depth(ctx);
205 if (depth > MAX_CERT_DEPTH) {
207 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
208 X509_STORE_CTX_set_error(ctx, err);
212 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
213 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
216 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
217 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
218 debug(DBG_WARN, "\tIssuer=%s", buf);
220 case X509_V_ERR_CERT_NOT_YET_VALID:
221 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
222 debug(DBG_WARN, "\tCertificate not yet valid");
224 case X509_V_ERR_CERT_HAS_EXPIRED:
225 debug(DBG_WARN, "Certificate has expired");
227 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
228 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
233 printf("certificate verify returns %d\n", ok);
238 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
239 struct addrinfo hints, *addrinfo, *res;
243 slash = conf->host ? strchr(conf->host, '/') : NULL;
247 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
251 if (*s < '0' || *s > '9') {
252 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
255 plen = atoi(slash + 1);
256 if (plen < 0 || plen > 128) {
257 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
262 memset(&hints, 0, sizeof(hints));
263 hints.ai_socktype = conf->pdef->socktype;
264 hints.ai_family = AF_UNSPEC;
265 hints.ai_flags = ai_flags;
266 if (!conf->host && !conf->port) {
267 /* getaddrinfo() doesn't like host and port to be NULL */
268 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
269 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
272 for (res = addrinfo; res; res = res->ai_next) {
273 switch (res->ai_family) {
275 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
278 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
284 hints.ai_flags |= AI_NUMERICHOST;
285 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
286 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
291 switch (addrinfo->ai_family) {
294 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
295 freeaddrinfo(addrinfo);
302 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
303 freeaddrinfo(addrinfo);
306 conf->prefixlen = plen;
308 conf->prefixlen = 255;
311 freeaddrinfo(conf->addrinfo);
312 conf->addrinfo = addrinfo;
316 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
318 struct addrinfo *res;
320 for (res = addrinfo; res; res = res->ai_next) {
321 if (family != AF_UNSPEC && family != res->ai_family)
323 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
325 debug(DBG_WARN, "bindtoaddr: socket failed");
329 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
332 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
335 if (!bind(s, res->ai_addr, res->ai_addrlen))
337 debug(DBG_WARN, "bindtoaddr: bind failed");
343 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
348 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
352 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
354 debugx(1, DBG_ERR, "no ] matching initial [");
358 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
361 debugx(1, DBG_ERR, "missing host/address");
363 conf->host = stringcopy(field, p - field);
366 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
367 debugx(1, DBG_ERR, "unexpected character after ]");
370 /* port number or service name is specified */;
372 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
374 debugx(1, DBG_ERR, "syntax error, : but no following port");
375 conf->port = stringcopy(field, p - field);
377 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
381 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
382 struct clsrvconf *conf;
384 conf = malloc(sizeof(struct clsrvconf));
386 debugx(1, DBG_ERR, "malloc failed");
387 memset(conf, 0, sizeof(struct clsrvconf));
389 conf->pdef = &protodefs[conf->type];
391 parsehostport(lconf, conf, default_port);
392 if (!strcmp(conf->host, "*")) {
397 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
398 if (!resolvepeer(conf, AI_PASSIVE))
399 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
403 void freeclsrvres(struct clsrvconf *res) {
407 freeaddrinfo(res->addrinfo);
411 int connecttcp(struct addrinfo *addrinfo, struct addrinfo *src) {
413 struct addrinfo *res;
416 for (res = addrinfo; res; res = res->ai_next) {
417 s = bindtoaddr(src, res->ai_family, 1, 1);
419 debug(DBG_WARN, "connecttoserver: socket failed");
422 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
424 debug(DBG_WARN, "connecttoserver: connect failed");
431 /* returns 1 if the len first bits are equal, else 0 */
432 int prefixmatch(void *a1, void *a2, uint8_t len) {
433 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
435 if (l && memcmp(a1, a2, l))
440 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
443 /* returns next config with matching address, or NULL */
444 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
445 struct sockaddr_in6 *sa6 = NULL;
446 struct in_addr *a4 = NULL;
447 struct addrinfo *res;
448 struct list_node *entry;
449 struct clsrvconf *conf;
451 if (addr->sa_family == AF_INET6) {
452 sa6 = (struct sockaddr_in6 *)addr;
453 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
454 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
458 a4 = &((struct sockaddr_in *)addr)->sin_addr;
460 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
461 conf = (struct clsrvconf *)entry->data;
462 if (conf->type == type) {
463 if (conf->prefixlen == 255) {
464 for (res = conf->addrinfo; res; res = res->ai_next)
465 if ((a4 && res->ai_family == AF_INET &&
466 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
467 (sa6 && res->ai_family == AF_INET6 &&
468 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
474 res = conf->addrinfo;
476 ((a4 && res->ai_family == AF_INET &&
477 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
478 (sa6 && res->ai_family == AF_INET6 &&
479 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
490 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
491 return find_conf(type, addr, clconfs, cur);
494 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
495 return find_conf(type, addr, srvconfs, cur);
498 /* returns next config of given type, or NULL */
499 struct clsrvconf *find_conf_type(uint8_t type, struct list *confs, struct list_node **cur) {
500 struct list_node *entry;
501 struct clsrvconf *conf;
503 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
504 conf = (struct clsrvconf *)entry->data;
505 if (conf->type == type) {
514 struct queue *newqueue() {
517 q = malloc(sizeof(struct queue));
519 debugx(1, DBG_ERR, "malloc failed");
520 q->entries = list_create();
522 debugx(1, DBG_ERR, "malloc failed");
523 pthread_mutex_init(&q->mutex, NULL);
524 pthread_cond_init(&q->cond, NULL);
528 void removequeue(struct queue *q) {
529 struct list_node *entry;
531 pthread_mutex_lock(&q->mutex);
532 for (entry = list_first(q->entries); entry; entry = list_next(entry))
533 free(((struct reply *)entry)->buf);
534 list_destroy(q->entries);
535 pthread_cond_destroy(&q->cond);
536 pthread_mutex_unlock(&q->mutex);
537 pthread_mutex_destroy(&q->mutex);
540 void freebios(struct queue *q) {
543 pthread_mutex_lock(&q->mutex);
544 while ((bio = (BIO *)list_shift(q->entries)))
546 pthread_mutex_unlock(&q->mutex);
550 struct client *addclient(struct clsrvconf *conf) {
551 struct client *new = malloc(sizeof(struct client));
554 debug(DBG_ERR, "malloc failed");
557 if (!conf->clients) {
558 conf->clients = list_create();
559 if (!conf->clients) {
560 debug(DBG_ERR, "malloc failed");
565 memset(new, 0, sizeof(struct client));
567 new->replyq = conf->type == RAD_UDP ? udp_server_replyq : newqueue();
568 if (conf->type == RAD_DTLS)
569 new->rbios = newqueue();
570 list_push(conf->clients, new);
574 void removeclient(struct client *client) {
575 if (!client || !client->conf->clients)
577 removequeue(client->replyq);
579 freebios(client->rbios);
580 list_removedata(client->conf->clients, client);
584 void removeclientrqs(struct client *client) {
585 struct list_node *entry;
586 struct server *server;
590 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
591 server = ((struct clsrvconf *)entry->data)->servers;
594 pthread_mutex_lock(&server->newrq_mutex);
595 for (i = 0; i < MAX_REQUESTS; i++) {
596 rq = server->requests + i;
597 if (rq->from == client)
600 pthread_mutex_unlock(&server->newrq_mutex);
604 void freeserver(struct server *server, uint8_t destroymutex) {
605 struct request *rq, *end;
610 if (server->requests) {
611 rq = server->requests;
612 for (end = rq + MAX_REQUESTS; rq < end; rq++)
614 free(server->requests);
617 freebios(server->rbios);
618 free(server->dynamiclookuparg);
620 pthread_mutex_destroy(&server->lock);
621 pthread_cond_destroy(&server->newrq_cond);
622 pthread_mutex_destroy(&server->newrq_mutex);
627 int addserver(struct clsrvconf *conf) {
628 struct clsrvconf *res;
632 debug(DBG_ERR, "addserver: currently works with just one server per conf");
635 conf->servers = malloc(sizeof(struct server));
636 if (!conf->servers) {
637 debug(DBG_ERR, "malloc failed");
640 memset(conf->servers, 0, sizeof(struct server));
641 conf->servers->conf = conf;
644 if (type == RAD_DTLS)
645 conf->servers->rbios = newqueue();
647 if (!srcprotores[type]) {
648 res = resolve_hostport(type, *conf->pdef->srcaddrport, NULL);
649 srcprotores[type] = res->addrinfo;
650 res->addrinfo = NULL;
656 switch (conf->addrinfo->ai_family) {
658 if (udp_client4_sock < 0) {
659 udp_client4_sock = bindtoaddr(srcprotores[RAD_UDP], AF_INET, 0, 1);
660 if (udp_client4_sock < 0)
661 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
663 conf->servers->sock = udp_client4_sock;
666 if (udp_client6_sock < 0) {
667 udp_client6_sock = bindtoaddr(srcprotores[RAD_UDP], AF_INET6, 0, 1);
668 if (udp_client6_sock < 0)
669 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
671 conf->servers->sock = udp_client6_sock;
674 debugx(1, DBG_ERR, "addserver: unsupported address family");
678 switch (conf->addrinfo->ai_family) {
680 if (dtls_client4_sock < 0) {
681 dtls_client4_sock = bindtoaddr(srcprotores[RAD_DTLS], AF_INET, 0, 1);
682 if (dtls_client4_sock < 0)
683 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
685 conf->servers->sock = dtls_client4_sock;
688 if (dtls_client6_sock < 0) {
689 dtls_client6_sock = bindtoaddr(srcprotores[RAD_DTLS], AF_INET6, 0, 1);
690 if (dtls_client6_sock < 0)
691 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
693 conf->servers->sock = dtls_client6_sock;
696 debugx(1, DBG_ERR, "addserver: unsupported address family");
700 conf->servers->sock = -1;
703 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
704 if (!conf->servers->requests) {
705 debug(DBG_ERR, "malloc failed");
708 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
709 debug(DBG_ERR, "mutex init failed");
712 conf->servers->newrq = 0;
713 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
714 debug(DBG_ERR, "mutex init failed");
715 pthread_mutex_destroy(&conf->servers->lock);
718 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
719 debug(DBG_ERR, "mutex init failed");
720 pthread_mutex_destroy(&conf->servers->newrq_mutex);
721 pthread_mutex_destroy(&conf->servers->lock);
728 freeserver(conf->servers, 0);
729 conf->servers = NULL;
733 /* exactly one of client and server must be non-NULL */
734 /* return who we received from in *client or *server */
735 /* return from in sa if not NULL */
736 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
738 unsigned char buf[4], *rad = NULL;
739 struct sockaddr_storage from;
740 socklen_t fromlen = sizeof(from);
742 struct list_node *node;
752 if (select(s + 1, &readfds, NULL, NULL, NULL) < 1)
754 cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
756 debug(DBG_WARN, "radudpget: recv failed");
760 debug(DBG_WARN, "radudpget: length too small");
765 p = find_conf(RAD_UDP, (struct sockaddr *)&from, client ? clconfs : srvconfs, NULL);
767 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
774 debug(DBG_WARN, "radudpget: length too small");
781 debug(DBG_ERR, "radudpget: malloc failed");
786 cnt = recv(s, rad, len, MSG_TRUNC);
787 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
790 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
794 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
797 node = list_first(p->clients);
798 *client = node ? (struct client *)node->data : addclient(p);
802 *server = p->servers;
810 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
811 int loc, i, l, n, r = 0;
814 STACK_OF(GENERAL_NAME) *alt;
817 debug(DBG_DBG, "subjectaltnameaddr");
819 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
823 ex = X509_get_ext(cert, loc);
824 alt = X509V3_EXT_d2i(ex);
828 n = sk_GENERAL_NAME_num(alt);
829 for (i = 0; i < n; i++) {
830 gn = sk_GENERAL_NAME_value(alt, i);
831 if (gn->type != GEN_IPADD)
834 v = (char *)ASN1_STRING_data(gn->d.ia5);
835 l = ASN1_STRING_length(gn->d.ia5);
836 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
837 && !memcmp(v, &addr, l)) {
842 GENERAL_NAMES_free(alt);
846 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
853 nm = X509_get_subject_name(cert);
856 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
859 e = X509_NAME_get_entry(nm, loc);
860 t = X509_NAME_ENTRY_get_data(e);
861 v = (char *) ASN1_STRING_data(t);
862 l = ASN1_STRING_length(t);
866 if (l == strlen(exact) && !strncasecmp(exact, v, l))
869 s = stringcopy((char *)v, l);
871 debug(DBG_ERR, "malloc failed");
874 if (regexec(regex, s, 0, NULL, 0)) {
885 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
886 int loc, i, l, n, r = 0;
889 STACK_OF(GENERAL_NAME) *alt;
892 debug(DBG_DBG, "subjectaltnameregexp");
894 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
898 ex = X509_get_ext(cert, loc);
899 alt = X509V3_EXT_d2i(ex);
903 n = sk_GENERAL_NAME_num(alt);
904 for (i = 0; i < n; i++) {
905 gn = sk_GENERAL_NAME_value(alt, i);
906 if (gn->type != type)
909 v = (char *)ASN1_STRING_data(gn->d.ia5);
910 l = ASN1_STRING_length(gn->d.ia5);
914 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
917 if (memcmp(v, exact, l))
920 s = stringcopy((char *)v, l);
922 debug(DBG_ERR, "malloc failed");
925 if (regexec(regex, s, 0, NULL, 0)) {
934 GENERAL_NAMES_free(alt);
938 X509 *verifytlscert(SSL *ssl) {
942 if (SSL_get_verify_result(ssl) != X509_V_OK) {
943 debug(DBG_ERR, "verifytlscert: basic validation failed");
944 while ((error = ERR_get_error()))
945 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
949 cert = SSL_get_peer_certificate(ssl);
951 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
955 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
957 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
958 struct in6_addr addr;
960 if (conf->certnamecheck && conf->prefixlen == 255) {
961 if (inet_pton(AF_INET, conf->host, &addr))
963 else if (inet_pton(AF_INET6, conf->host, &addr))
966 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
969 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
972 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
974 if (!cnregexp(cert, conf->host, NULL)) {
975 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
978 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
981 if (conf->certcnregex) {
982 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
983 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
986 debug(DBG_DBG, "verifyconfcert: CN matching regex");
988 if (conf->certuriregex) {
989 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
990 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
993 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
998 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
1002 unsigned long error;
1004 debug(DBG_DBG, "tlsconnect: called from %s", text);
1005 pthread_mutex_lock(&server->lock);
1006 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
1007 /* already reconnected, nothing to do */
1008 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
1009 pthread_mutex_unlock(&server->lock);
1014 gettimeofday(&now, NULL);
1015 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
1016 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
1017 debug(DBG_DBG, "tlsconnect: timeout");
1018 if (server->sock >= 0)
1019 close(server->sock);
1020 SSL_free(server->ssl);
1022 pthread_mutex_unlock(&server->lock);
1025 if (server->connectionok) {
1026 server->connectionok = 0;
1028 } else if (elapsed < 1)
1030 else if (elapsed < 60) {
1031 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
1033 } else if (elapsed < 100000) {
1034 debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
1037 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
1038 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
1039 if (server->sock >= 0)
1040 close(server->sock);
1041 if ((server->sock = connecttcp(server->conf->addrinfo, srcprotores[RAD_TLS])) < 0) {
1042 debug(DBG_ERR, "tlsconnect: connecttcp failed");
1046 SSL_free(server->ssl);
1047 server->ssl = SSL_new(server->conf->ssl_ctx);
1048 SSL_set_fd(server->ssl, server->sock);
1049 if (SSL_connect(server->ssl) <= 0) {
1050 while ((error = ERR_get_error()))
1051 debug(DBG_ERR, "tlsconnect: TLS: %s", ERR_error_string(error, NULL));
1054 cert = verifytlscert(server->ssl);
1057 if (verifyconfcert(cert, server->conf)) {
1063 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
1064 gettimeofday(&server->lastconnecttry, NULL);
1065 pthread_mutex_unlock(&server->lock);
1069 int tcpconnect(struct server *server, struct timeval *when, int timeout, char *text) {
1073 debug(DBG_DBG, "tcpconnect: called from %s", text);
1074 pthread_mutex_lock(&server->lock);
1075 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
1076 /* already reconnected, nothing to do */
1077 debug(DBG_DBG, "tcpconnect(%s): seems already reconnected", text);
1078 pthread_mutex_unlock(&server->lock);
1083 gettimeofday(&now, NULL);
1084 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
1085 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
1086 debug(DBG_DBG, "tcpconnect: timeout");
1087 if (server->sock >= 0)
1088 close(server->sock);
1089 pthread_mutex_unlock(&server->lock);
1092 if (server->connectionok) {
1093 server->connectionok = 0;
1095 } else if (elapsed < 1)
1097 else if (elapsed < 60) {
1098 debug(DBG_INFO, "tcpconnect: sleeping %lds", elapsed);
1100 } else if (elapsed < 100000) {
1101 debug(DBG_INFO, "tcpconnect: sleeping %ds", 60);
1104 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
1105 debug(DBG_WARN, "tcpconnect: trying to open TCP connection to %s port %s", server->conf->host, server->conf->port);
1106 if (server->sock >= 0)
1107 close(server->sock);
1108 if ((server->sock = connecttcp(server->conf->addrinfo, srcprotores[RAD_TCP])) >= 0)
1110 debug(DBG_ERR, "tcpconnect: connecttcp failed");
1112 debug(DBG_WARN, "tcpconnect: TCP connection to %s port %s up", server->conf->host, server->conf->port);
1113 gettimeofday(&server->lastconnecttry, NULL);
1114 pthread_mutex_unlock(&server->lock);
1118 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
1119 /* returns 0 on timeout, -1 on error and num if ok */
1120 int sslreadtimeout(SSL *ssl, unsigned char *buf, int num, int timeout) {
1121 int s, ndesc, cnt, len;
1122 fd_set readfds, writefds;
1123 struct timeval timer;
1125 s = SSL_get_fd(ssl);
1128 /* make socket non-blocking? */
1129 for (len = 0; len < num; len += cnt) {
1131 FD_SET(s, &readfds);
1134 timer.tv_sec = timeout;
1137 ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
1141 cnt = SSL_read(ssl, buf + len, num - len);
1143 switch (SSL_get_error(ssl, cnt)) {
1144 case SSL_ERROR_WANT_READ:
1145 case SSL_ERROR_WANT_WRITE:
1148 case SSL_ERROR_ZERO_RETURN:
1149 /* remote end sent close_notify, send one back */
1159 /* timeout in seconds, 0 means no timeout (blocking) */
1160 unsigned char *radtlsget(SSL *ssl, int timeout) {
1162 unsigned char buf[4], *rad;
1165 cnt = sslreadtimeout(ssl, buf, 4, timeout);
1167 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1174 debug(DBG_ERR, "radtlsget: malloc failed");
1177 memcpy(rad, buf, 4);
1179 cnt = sslreadtimeout(ssl, rad + 4, len - 4, timeout);
1181 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1190 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
1193 debug(DBG_DBG, "radtlsget: got %d bytes", len);
1197 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
1198 /* returns 0 on timeout, -1 on error and num if ok */
1199 int tcpreadtimeout(int s, unsigned char *buf, int num, int timeout) {
1200 int ndesc, cnt, len;
1201 fd_set readfds, writefds;
1202 struct timeval timer;
1206 /* make socket non-blocking? */
1207 for (len = 0; len < num; len += cnt) {
1209 FD_SET(s, &readfds);
1212 timer.tv_sec = timeout;
1215 ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
1219 cnt = read(s, buf + len, num - len);
1226 /* timeout in seconds, 0 means no timeout (blocking) */
1227 unsigned char *radtcpget(int s, int timeout) {
1229 unsigned char buf[4], *rad;
1232 cnt = tcpreadtimeout(s, buf, 4, timeout);
1234 debug(DBG_DBG, cnt ? "radtcpget: connection lost" : "radtcpget: timeout");
1241 debug(DBG_ERR, "radtcpget: malloc failed");
1244 memcpy(rad, buf, 4);
1246 cnt = tcpreadtimeout(s, rad + 4, len - 4, timeout);
1248 debug(DBG_DBG, cnt ? "radtcpget: connection lost" : "radtcpget: timeout");
1257 debug(DBG_WARN, "radtcpget: packet smaller than minimum radius size");
1260 debug(DBG_DBG, "radtcpget: got %d bytes", len);
1264 int clientradputudp(struct server *server, unsigned char *rad) {
1266 struct sockaddr_storage sa;
1267 struct sockaddr *sap;
1268 struct clsrvconf *conf = server->conf;
1269 in_port_t *port = NULL;
1273 if (*rad == RAD_Accounting_Request) {
1274 sap = (struct sockaddr *)&sa;
1275 memcpy(sap, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen);
1277 sap = conf->addrinfo->ai_addr;
1279 switch (sap->sa_family) {
1281 port = &((struct sockaddr_in *)sap)->sin_port;
1284 port = &((struct sockaddr_in6 *)sap)->sin6_port;
1290 if (*rad == RAD_Accounting_Request)
1291 *port = htons(ntohs(*port) + 1);
1293 if (sendto(server->sock, rad, len, 0, sap, conf->addrinfo->ai_addrlen) >= 0) {
1294 debug(DBG_DBG, "clienradputudp: sent UDP of length %d to %s port %d", len, conf->host, ntohs(*port));
1298 debug(DBG_WARN, "clientradputudp: send failed");
1302 int clientradputtls(struct server *server, unsigned char *rad) {
1305 unsigned long error;
1306 struct timeval lastconnecttry;
1307 struct clsrvconf *conf = server->conf;
1310 lastconnecttry = server->lastconnecttry;
1311 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
1312 while ((error = ERR_get_error()))
1313 debug(DBG_ERR, "clientradputtls: TLS: %s", ERR_error_string(error, NULL));
1314 if (server->dynamiclookuparg)
1316 tlsconnect(server, &lastconnecttry, 0, "clientradputtls");
1317 lastconnecttry = server->lastconnecttry;
1320 server->connectionok = 1;
1321 debug(DBG_DBG, "clientradputtls: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
1325 int clientradputtcp(struct server *server, unsigned char *rad) {
1328 struct timeval lastconnecttry;
1329 struct clsrvconf *conf = server->conf;
1332 lastconnecttry = server->lastconnecttry;
1333 while ((cnt = write(server->sock, rad, len)) <= 0) {
1334 debug(DBG_ERR, "clientradputtcp: write error");
1335 tcpconnect(server, &lastconnecttry, 0, "clientradputtcp");
1336 lastconnecttry = server->lastconnecttry;
1339 server->connectionok = 1;
1340 debug(DBG_DBG, "clientradputtcp: Sent %d bytes, Radius packet of length %d to TCP peer %s", cnt, len, conf->host);
1344 int radsign(unsigned char *rad, unsigned char *sec) {
1345 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1346 static unsigned char first = 1;
1347 static EVP_MD_CTX mdctx;
1348 unsigned int md_len;
1351 pthread_mutex_lock(&lock);
1353 EVP_MD_CTX_init(&mdctx);
1357 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1358 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
1359 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1360 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
1362 pthread_mutex_unlock(&lock);
1366 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
1367 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1368 static unsigned char first = 1;
1369 static EVP_MD_CTX mdctx;
1370 unsigned char hash[EVP_MAX_MD_SIZE];
1374 pthread_mutex_lock(&lock);
1376 EVP_MD_CTX_init(&mdctx);
1382 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1383 EVP_DigestUpdate(&mdctx, rad, 4) &&
1384 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
1385 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
1386 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1387 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
1389 !memcmp(hash, rad + 4, 16));
1390 pthread_mutex_unlock(&lock);
1394 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
1395 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1396 static unsigned char first = 1;
1397 static HMAC_CTX hmacctx;
1398 unsigned int md_len;
1399 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
1401 pthread_mutex_lock(&lock);
1403 HMAC_CTX_init(&hmacctx);
1407 memcpy(auth, authattr, 16);
1408 memset(authattr, 0, 16);
1410 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1411 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1412 HMAC_Final(&hmacctx, hash, &md_len);
1413 memcpy(authattr, auth, 16);
1415 debug(DBG_WARN, "message auth computation failed");
1416 pthread_mutex_unlock(&lock);
1420 if (memcmp(auth, hash, 16)) {
1421 debug(DBG_WARN, "message authenticator, wrong value");
1422 pthread_mutex_unlock(&lock);
1426 pthread_mutex_unlock(&lock);
1430 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
1431 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1432 static unsigned char first = 1;
1433 static HMAC_CTX hmacctx;
1434 unsigned int md_len;
1439 pthread_mutex_lock(&lock);
1441 HMAC_CTX_init(&hmacctx);
1445 memset(authattrval, 0, 16);
1447 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1448 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1449 HMAC_Final(&hmacctx, authattrval, &md_len);
1451 debug(DBG_WARN, "message auth computation failed");
1452 pthread_mutex_unlock(&lock);
1456 pthread_mutex_unlock(&lock);
1460 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
1461 while (length > 1) {
1462 if (ATTRTYPE(attrs) == type)
1464 length -= ATTRLEN(attrs);
1465 attrs += ATTRLEN(attrs);
1470 void freerqdata(struct request *rq) {
1471 if (rq->origusername)
1472 free(rq->origusername);
1477 void sendrq(struct server *to, struct request *rq) {
1481 pthread_mutex_lock(&to->newrq_mutex);
1482 /* might simplify if only try nextid, might be ok */
1483 for (i = to->nextid; i < MAX_REQUESTS; i++)
1484 if (!to->requests[i].buf)
1486 if (i == MAX_REQUESTS) {
1487 for (i = 0; i < to->nextid; i++)
1488 if (!to->requests[i].buf)
1490 if (i == to->nextid) {
1491 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
1497 rq->buf[1] = (char)i;
1499 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1500 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1505 if (*rq->buf == RAD_Accounting_Request) {
1506 if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
1507 debug(DBG_WARN, "sendrq: failed to sign Accounting-Request message");
1513 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1514 to->requests[i] = *rq;
1519 debug(DBG_DBG, "sendrq: signalling client writer");
1520 pthread_cond_signal(&to->newrq_cond);
1523 pthread_mutex_unlock(&to->newrq_mutex);
1526 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa, int toudpsock) {
1527 struct reply *reply;
1530 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1532 debug(DBG_WARN, "sendreply: failed to sign message");
1536 reply = malloc(sizeof(struct reply));
1539 debug(DBG_ERR, "sendreply: malloc failed");
1542 memset(reply, 0, sizeof(struct reply));
1545 reply->tosa = *tosa;
1546 reply->toudpsock = toudpsock;
1548 pthread_mutex_lock(&to->replyq->mutex);
1550 first = list_first(to->replyq->entries) == NULL;
1552 if (!list_push(to->replyq->entries, reply)) {
1553 pthread_mutex_unlock(&to->replyq->mutex);
1556 debug(DBG_ERR, "sendreply: malloc failed");
1561 debug(DBG_DBG, "signalling server writer");
1562 pthread_cond_signal(&to->replyq->cond);
1564 pthread_mutex_unlock(&to->replyq->mutex);
1567 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1568 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1569 static unsigned char first = 1;
1570 static EVP_MD_CTX mdctx;
1571 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1572 unsigned int md_len;
1573 uint8_t i, offset = 0, out[128];
1575 pthread_mutex_lock(&lock);
1577 EVP_MD_CTX_init(&mdctx);
1583 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1584 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1585 !EVP_DigestUpdate(&mdctx, input, 16) ||
1586 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1588 pthread_mutex_unlock(&lock);
1591 for (i = 0; i < 16; i++)
1592 out[offset + i] = hash[i] ^ in[offset + i];
1593 input = out + offset - 16;
1598 memcpy(in, out, len);
1599 pthread_mutex_unlock(&lock);
1603 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1604 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1605 static unsigned char first = 1;
1606 static EVP_MD_CTX mdctx;
1607 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1608 unsigned int md_len;
1609 uint8_t i, offset = 0, out[128];
1611 pthread_mutex_lock(&lock);
1613 EVP_MD_CTX_init(&mdctx);
1619 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1620 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1621 !EVP_DigestUpdate(&mdctx, input, 16) ||
1622 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1624 pthread_mutex_unlock(&lock);
1627 for (i = 0; i < 16; i++)
1628 out[offset + i] = hash[i] ^ in[offset + i];
1629 input = in + offset;
1634 memcpy(in, out, len);
1635 pthread_mutex_unlock(&lock);
1639 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1640 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1641 static unsigned char first = 1;
1642 static EVP_MD_CTX mdctx;
1643 unsigned char hash[EVP_MAX_MD_SIZE];
1644 unsigned int md_len;
1647 pthread_mutex_lock(&lock);
1649 EVP_MD_CTX_init(&mdctx);
1654 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1655 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1656 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1659 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1660 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1661 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1662 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1663 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1664 pthread_mutex_unlock(&lock);
1669 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1672 for (i = 0; i < 16; i++)
1675 for (offset = 16; offset < len; offset += 16) {
1677 printf("text + offset - 16 c(%d): ", offset / 16);
1678 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1680 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1681 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1682 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1683 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1685 pthread_mutex_unlock(&lock);
1689 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1692 for (i = 0; i < 16; i++)
1693 text[offset + i] ^= hash[i];
1697 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1700 pthread_mutex_unlock(&lock);
1704 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1705 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1706 static unsigned char first = 1;
1707 static EVP_MD_CTX mdctx;
1708 unsigned char hash[EVP_MAX_MD_SIZE];
1709 unsigned int md_len;
1713 pthread_mutex_lock(&lock);
1715 EVP_MD_CTX_init(&mdctx);
1720 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1721 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1722 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1725 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1726 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1727 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1728 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1729 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1730 pthread_mutex_unlock(&lock);
1735 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1738 for (i = 0; i < 16; i++)
1739 plain[i] = text[i] ^ hash[i];
1741 for (offset = 16; offset < len; offset += 16) {
1743 printf("text + offset - 16 c(%d): ", offset / 16);
1744 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1746 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1747 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1748 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1749 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1751 pthread_mutex_unlock(&lock);
1755 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1758 for (i = 0; i < 16; i++)
1759 plain[offset + i] = text[offset + i] ^ hash[i];
1762 memcpy(text, plain, len);
1764 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1767 pthread_mutex_unlock(&lock);
1771 struct realm *id2realm(struct list *realmlist, char *id) {
1772 struct list_node *entry;
1773 struct realm *realm, *subrealm = NULL;
1775 /* need to do locking for subrealms and check subrealm timers */
1776 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1777 realm = (struct realm *)entry->data;
1778 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1779 pthread_mutex_lock(&realm->subrealms_mutex);
1780 if (realm->subrealms)
1781 subrealm = id2realm(realm->subrealms, id);
1782 pthread_mutex_unlock(&realm->subrealms_mutex);
1783 return subrealm ? subrealm : realm;
1789 /* helper function, only used by removeserversubrealms() */
1790 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1791 struct list_node *entry;
1792 struct realm *realm;
1794 for (entry = list_first(realmlist); entry;) {
1795 realm = (struct realm *)entry->data;
1796 entry = list_next(entry);
1797 if (realm->srvconfs) {
1798 list_removedata(realm->srvconfs, srv);
1799 if (!list_first(realm->srvconfs)) {
1800 list_destroy(realm->srvconfs);
1801 realm->srvconfs = NULL;
1804 if (realm->accsrvconfs) {
1805 list_removedata(realm->accsrvconfs, srv);
1806 if (!list_first(realm->accsrvconfs)) {
1807 list_destroy(realm->accsrvconfs);
1808 realm->accsrvconfs = NULL;
1812 /* remove subrealm if no servers */
1813 if (!realm->srvconfs && !realm->accsrvconfs) {
1814 list_removedata(realmlist, realm);
1820 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1821 struct list_node *entry;
1822 struct realm *realm;
1824 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1825 realm = (struct realm *)entry->data;
1826 pthread_mutex_lock(&realm->subrealms_mutex);
1827 if (realm->subrealms) {
1828 _internal_removeserversubrealms(realm->subrealms, srv);
1829 if (!list_first(realm->subrealms)) {
1830 list_destroy(realm->subrealms);
1831 realm->subrealms = NULL;
1834 pthread_mutex_unlock(&realm->subrealms_mutex);
1838 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1839 struct request *rq = to->requests, *end;
1841 pthread_mutex_lock(&to->newrq_mutex);
1842 for (end = rq + MAX_REQUESTS; rq < end; rq++)
1843 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1845 pthread_mutex_unlock(&to->newrq_mutex);
1850 int attrvalidate(unsigned char *attrs, int length) {
1851 while (length > 1) {
1852 if (ATTRLEN(attrs) < 2) {
1853 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1856 length -= ATTRLEN(attrs);
1858 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1861 attrs += ATTRLEN(attrs);
1864 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1868 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1869 if (len < 16 || len > 128 || len % 16) {
1870 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1874 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1875 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1879 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1881 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1882 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1888 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1891 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1892 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1895 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1896 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1902 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1903 char *oldsecret, char *newsecret) {
1904 unsigned char *attr;
1906 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1907 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1908 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1914 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1918 for (; attrs[0]; attrs += 2)
1919 if (attrs[0] == vendor && attrs[1] == subattr)
1924 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1925 uint8_t alen, sublen, rmlen = 0;
1926 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1929 if (!removevendorattrs)
1932 while (*removevendorattrs && *removevendorattrs != vendor)
1933 removevendorattrs += 2;
1934 if (!*removevendorattrs)
1937 alen = ATTRLEN(attrs);
1939 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1940 /* remove entire vendor attribute */
1941 memmove(attrs, attrs + alen, length - alen);
1946 subattrs = ATTRVAL(attrs) + 4;
1948 if (!attrvalidate(subattrs, sublen)) {
1949 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1954 while (sublen > 1) {
1955 alen = ATTRLEN(subattrs);
1958 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1959 memmove(subattrs, subattrs + alen, length);
1965 ATTRLEN(attrs) -= rmlen;
1969 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1970 uint8_t *attrs, alen;
1971 uint16_t len, rmlen = 0;
1973 if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1976 len = RADLEN(buf) - 20;
1979 alen = ATTRLEN(attrs);
1981 if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1982 memmove(attrs, attrs + alen, len);
1984 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1985 rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1990 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1993 /* returns a pointer to the resized attribute value */
1994 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1995 uint8_t *attrs, *attr, vallen;
1999 len = RADLEN(*buf) - 20;
2002 attr = attrget(attrs, len, type);
2006 vallen = ATTRVALLEN(attr);
2007 if (vallen == newvallen)
2010 len += newvallen - vallen;
2011 if (newvallen > vallen) {
2012 new = realloc(*buf, len + 20);
2014 debug(DBG_ERR, "resizeattr: malloc failed");
2023 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
2024 attr[1] = newvallen + 2;
2025 ((uint16_t *)*buf)[1] = htons(len + 20);
2029 int rewriteusername(struct request *rq, char *in) {
2030 size_t nmatch = 10, reslen = 0, start = 0;
2031 regmatch_t pmatch[10], *pfield;
2033 unsigned char *result;
2034 char *out = rq->from->conf->rewriteattrreplacement;
2036 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
2037 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
2041 rq->origusername = stringcopy(in, 0);
2042 if (!rq->origusername)
2045 for (i = start; out[i]; i++) {
2046 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
2047 pfield = &pmatch[out[i + 1] - '0'];
2048 if (pfield->rm_so >= 0) {
2049 reslen += i - start + pfield->rm_eo - pfield->rm_so;
2055 reslen += i - start;
2057 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
2063 for (i = start; out[i]; i++) {
2064 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
2065 pfield = &pmatch[out[i + 1] - '0'];
2066 if (pfield->rm_so >= 0) {
2067 memcpy(result + reslen, out + start, i - start);
2068 reslen += i - start;
2069 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
2070 reslen += pfield->rm_eo - pfield->rm_so;
2077 memcpy(result + reslen, out + start, i - start);
2078 reslen += i - start;
2079 memcpy(in, result, reslen);
2084 const char *radmsgtype2string(uint8_t code) {
2085 static const char *rad_msg_names[] = {
2086 "", "Access-Request", "Access-Accept", "Access-Reject",
2087 "Accounting-Request", "Accounting-Response", "", "",
2088 "", "", "", "Access-Challenge",
2089 "Status-Server", "Status-Client"
2091 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
2094 void char2hex(char *h, unsigned char c) {
2095 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
2096 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
2097 h[0] = hexdigits[c / 16];
2098 h[1] = hexdigits[c % 16];
2102 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
2106 if (!attr || len == 1) {
2111 l = ATTRVALLEN(attr);
2112 s = (char *)ATTRVAL(attr);
2115 for (i = 0; i < l; i++) {
2116 if (s[i] > 31 && s[i] < 127) {
2118 if (d - ascii == len - 1)
2121 if (d - ascii > len - 4)
2126 if (d - ascii == len - 1)
2134 void acclog(unsigned char *attrs, int length, char *host) {
2135 unsigned char *attr;
2138 attr = attrget(attrs, length, RAD_Attr_User_Name);
2140 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
2143 radattr2ascii(username, sizeof(username), attr);
2144 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
2147 void respondaccounting(struct request *rq) {
2148 unsigned char *resp;
2152 debug(DBG_ERR, "respondaccounting: malloc failed");
2155 memcpy(resp, rq->buf, 20);
2156 resp[0] = RAD_Accounting_Response;
2159 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
2160 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2163 void respondstatusserver(struct request *rq) {
2164 unsigned char *resp;
2168 debug(DBG_ERR, "respondstatusserver: malloc failed");
2171 memcpy(resp, rq->buf, 20);
2172 resp[0] = RAD_Access_Accept;
2175 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
2176 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2179 void respondreject(struct request *rq, char *message) {
2180 unsigned char *resp;
2183 if (message && *message)
2184 len += 2 + strlen(message);
2188 debug(DBG_ERR, "respondreject: malloc failed");
2191 memcpy(resp, rq->buf, 20);
2192 resp[0] = RAD_Access_Reject;
2193 *(uint16_t *)(resp + 2) = htons(len);
2194 if (message && *message) {
2195 resp[20] = RAD_Attr_Reply_Message;
2196 resp[21] = len - 20;
2197 memcpy(resp + 22, message, len - 22);
2199 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2202 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
2203 struct list_node *entry;
2204 struct clsrvconf *server, *best = NULL, *first = NULL;
2206 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2207 server = (struct clsrvconf *)entry->data;
2208 if (!server->servers)
2212 if (!server->servers->connectionok)
2214 if (!server->servers->lostrqs)
2220 if (server->servers->lostrqs < best->servers->lostrqs)
2223 return best ? best : first;
2226 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
2227 struct clsrvconf *srvconf;
2229 *realm = id2realm(realms, id);
2232 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
2233 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
2236 if (!acc && !srvconf->servers)
2237 adddynamicrealmserver(*realm, srvconf, id);
2238 return srvconf->servers;
2241 /* returns 0 if validation/authentication fails, else 1 */
2242 int radsrv(struct request *rq) {
2243 uint8_t code, id, *auth, *attrs, *attr;
2245 struct server *to = NULL;
2246 char username[254], userascii[760];
2247 unsigned char newauth[16];
2248 struct realm *realm = NULL;
2250 code = *(uint8_t *)rq->buf;
2251 id = *(uint8_t *)(rq->buf + 1);
2252 len = RADLEN(rq->buf);
2253 auth = (uint8_t *)(rq->buf + 4);
2255 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
2257 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
2258 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
2263 attrs = rq->buf + 20;
2265 if (!attrvalidate(attrs, len)) {
2266 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
2270 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2271 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
2272 debug(DBG_WARN, "radsrv: message authentication failed");
2276 if (code == RAD_Status_Server) {
2277 respondstatusserver(rq);
2281 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
2283 if (code == RAD_Accounting_Request) {
2284 memset(newauth, 0, 16);
2285 if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
2286 debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
2291 if (rq->from->conf->rewrite) {
2292 dorewrite(rq->buf, rq->from->conf->rewrite);
2293 len = RADLEN(rq->buf) - 20;
2296 attr = attrget(attrs, len, RAD_Attr_User_Name);
2298 if (code == RAD_Accounting_Request) {
2299 acclog(attrs, len, rq->from->conf->host);
2300 respondaccounting(rq);
2302 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
2305 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
2306 username[ATTRVALLEN(attr)] = '\0';
2307 radattr2ascii(userascii, sizeof(userascii), attr);
2309 if (rq->from->conf->rewriteattrregex) {
2310 if (!rewriteusername(rq, username)) {
2311 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
2314 len = RADLEN(rq->buf) - 20;
2315 auth = (uint8_t *)(rq->buf + 4);
2316 attrs = rq->buf + 20;
2319 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
2321 to = findserver(&realm, username, code == RAD_Accounting_Request);
2323 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
2327 if (realm->message && code == RAD_Access_Request) {
2328 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
2329 respondreject(rq, realm->message);
2330 } else if (realm->accresp && code == RAD_Accounting_Request) {
2331 acclog(attrs, len, rq->from->conf->host);
2332 respondaccounting(rq);
2337 if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
2338 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
2339 rq->from->conf->name, to->conf->name);
2343 if (rqinqueue(to, rq->from, id, code)) {
2344 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
2345 radmsgtype2string(code), rq->from->conf->host, id);
2349 if (code != RAD_Accounting_Request) {
2350 if (!RAND_bytes(newauth, 16)) {
2351 debug(DBG_WARN, "radsrv: failed to generate random auth");
2357 printfchars(NULL, "auth", "%02x ", auth, 16);
2360 attr = attrget(attrs, len, RAD_Attr_User_Password);
2362 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
2363 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2367 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
2369 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
2370 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2375 memcpy(rq->origauth, auth, 16);
2376 memcpy(auth, newauth, 16);
2389 int replyh(struct server *server, unsigned char *buf) {
2390 struct client *from;
2393 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
2394 struct sockaddr_storage fromsa;
2395 char tmp[760], stationid[760];
2397 server->connectionok = 1;
2398 server->lostrqs = 0;
2400 i = buf[1]; /* i is the id */
2402 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
2403 && *buf != RAD_Accounting_Response) {
2404 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
2407 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
2409 rq = server->requests + i;
2411 pthread_mutex_lock(&server->newrq_mutex);
2412 if (!rq->buf || !rq->tries) {
2413 pthread_mutex_unlock(&server->newrq_mutex);
2414 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
2419 pthread_mutex_unlock(&server->newrq_mutex);
2420 debug(DBG_INFO, "replyh: already received, ignoring reply");
2424 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
2425 pthread_mutex_unlock(&server->newrq_mutex);
2426 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
2430 len = RADLEN(buf) - 20;
2433 if (!attrvalidate(attrs, len)) {
2434 pthread_mutex_unlock(&server->newrq_mutex);
2435 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
2439 /* Message Authenticator */
2440 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2442 if (ATTRVALLEN(messageauth) != 16) {
2443 pthread_mutex_unlock(&server->newrq_mutex);
2444 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
2447 memcpy(tmp, buf + 4, 16);
2448 memcpy(buf + 4, rq->buf + 4, 16);
2449 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
2450 pthread_mutex_unlock(&server->newrq_mutex);
2451 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
2454 memcpy(buf + 4, tmp, 16);
2455 debug(DBG_DBG, "replyh: message auth ok");
2458 gettimeofday(&server->lastrcv, NULL);
2460 if (*rq->buf == RAD_Status_Server) {
2462 pthread_mutex_unlock(&server->newrq_mutex);
2463 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2467 gettimeofday(&server->lastreply, NULL);
2471 pthread_mutex_unlock(&server->newrq_mutex);
2472 debug(DBG_INFO, "replyh: client gone, ignoring reply");
2476 if (server->conf->rewrite) {
2477 dorewrite(buf, server->conf->rewrite);
2478 len = RADLEN(buf) - 20;
2482 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2483 if (ATTRVALLEN(attr) <= 4)
2486 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
2489 sublen = ATTRVALLEN(attr) - 4;
2490 subattrs = ATTRVAL(attr) + 4;
2491 if (!attrvalidate(subattrs, sublen) ||
2492 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2493 rq, server->conf->secret, from->conf->secret) ||
2494 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2495 rq, server->conf->secret, from->conf->secret))
2499 pthread_mutex_unlock(&server->newrq_mutex);
2500 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2504 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2505 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2507 radattr2ascii(tmp, sizeof(tmp), attr);
2508 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2510 radattr2ascii(stationid, sizeof(stationid), attr);
2511 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2512 radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2514 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2518 buf[1] = (char)rq->origid;
2519 memcpy(buf + 4, rq->origauth, 16);
2521 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2524 if (rq->origusername) {
2525 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2527 pthread_mutex_unlock(&server->newrq_mutex);
2528 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2531 memcpy(username, rq->origusername, strlen(rq->origusername));
2532 len = RADLEN(buf) - 20;
2535 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2539 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2540 pthread_mutex_unlock(&server->newrq_mutex);
2541 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2544 debug(DBG_DBG, "replyh: computed messageauthattr");
2547 fromsa = rq->fromsa; /* only needed for UDP */
2548 /* once we set received = 1, rq may be reused */
2551 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2552 sendreply(from, buf, &fromsa, rq->fromudpsock);
2553 pthread_mutex_unlock(&server->newrq_mutex);
2557 void *udpclientrd(void *arg) {
2558 struct server *server;
2560 int *s = (int *)arg;
2564 buf = radudpget(*s, NULL, &server, NULL);
2565 if (!replyh(server, buf))
2570 void *tlsclientrd(void *arg) {
2571 struct server *server = (struct server *)arg;
2573 struct timeval now, lastconnecttry;
2576 /* yes, lastconnecttry is really necessary */
2577 lastconnecttry = server->lastconnecttry;
2578 buf = radtlsget(server->ssl, server->dynamiclookuparg ? IDLE_TIMEOUT : 0);
2580 if (server->dynamiclookuparg)
2582 tlsconnect(server, &lastconnecttry, 0, "tlsclientrd");
2586 if (!replyh(server, buf))
2588 if (server->dynamiclookuparg) {
2589 gettimeofday(&now, NULL);
2590 if (now.tv_sec - server->lastreply.tv_sec > IDLE_TIMEOUT) {
2591 debug(DBG_INFO, "tlsclientrd: idle timeout for %s", server->conf->name);
2596 ERR_remove_state(0);
2597 server->clientrdgone = 1;
2601 void *tcpclientrd(void *arg) {
2602 struct server *server = (struct server *)arg;
2604 struct timeval lastconnecttry;
2607 /* yes, lastconnecttry is really necessary */
2608 lastconnecttry = server->lastconnecttry;
2609 buf = radtcpget(server->sock, 0);
2611 tcpconnect(server, &lastconnecttry, 0, "tcpclientrd");
2615 if (!replyh(server, buf))
2618 server->clientrdgone = 1;
2622 /* code for removing state not finished */
2623 void *clientwr(void *arg) {
2624 struct server *server = (struct server *)arg;
2626 pthread_t clientrdth;
2627 int i, dynconffail = 0;
2630 struct timespec timeout;
2631 struct request statsrvrq;
2632 unsigned char statsrvbuf[38];
2633 struct clsrvconf *conf;
2635 conf = server->conf;
2637 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2642 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2643 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2647 memset(&timeout, 0, sizeof(struct timespec));
2649 if (conf->statusserver) {
2650 memset(&statsrvrq, 0, sizeof(struct request));
2651 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2652 statsrvbuf[0] = RAD_Status_Server;
2654 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2655 statsrvbuf[21] = 18;
2656 gettimeofday(&server->lastrcv, NULL);
2659 if (conf->pdef->connecter) {
2660 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2662 server->connectionok = 1;
2663 if (pthread_create(&clientrdth, NULL, conf->pdef->clientreader, (void *)server)) {
2664 debug(DBG_ERR, "clientwr: pthread_create failed");
2668 server->connectionok = 1;
2671 pthread_mutex_lock(&server->newrq_mutex);
2672 if (!server->newrq) {
2673 gettimeofday(&now, NULL);
2674 /* random 0-7 seconds */
2675 RAND_bytes(&rnd, 1);
2677 if (conf->statusserver) {
2678 if (!timeout.tv_sec || timeout.tv_sec > server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd)
2679 timeout.tv_sec = server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd;
2681 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2682 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2685 if (timeout.tv_sec > now.tv_sec)
2686 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2688 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2691 if (server->newrq) {
2692 debug(DBG_DBG, "clientwr: got new request");
2697 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2699 pthread_mutex_unlock(&server->newrq_mutex);
2701 for (i = 0; i < MAX_REQUESTS; i++) {
2702 if (server->clientrdgone) {
2703 pthread_join(clientrdth, NULL);
2706 pthread_mutex_lock(&server->newrq_mutex);
2707 while (i < MAX_REQUESTS && !server->requests[i].buf)
2709 if (i == MAX_REQUESTS) {
2710 pthread_mutex_unlock(&server->newrq_mutex);
2713 rq = server->requests + i;
2716 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2718 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2720 /* setting this to NULL means that it can be reused */
2723 pthread_mutex_unlock(&server->newrq_mutex);
2727 gettimeofday(&now, NULL);
2728 if (now.tv_sec < rq->expiry.tv_sec) {
2729 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2730 timeout.tv_sec = rq->expiry.tv_sec;
2731 pthread_mutex_unlock(&server->newrq_mutex);
2735 if (rq->tries == (*rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2736 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2737 if (conf->statusserver) {
2738 if (*rq->buf == RAD_Status_Server) {
2739 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2740 if (server->lostrqs < 255)
2744 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2745 if (server->lostrqs < 255)
2749 /* setting this to NULL means that it can be reused */
2751 pthread_mutex_unlock(&server->newrq_mutex);
2754 pthread_mutex_unlock(&server->newrq_mutex);
2756 rq->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2757 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2758 timeout.tv_sec = rq->expiry.tv_sec;
2760 conf->pdef->clientradput(server, server->requests[i].buf);
2762 if (conf->statusserver) {
2763 gettimeofday(&now, NULL);
2764 if (now.tv_sec - server->lastrcv.tv_sec >= STATUS_SERVER_PERIOD) {
2765 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2766 debug(DBG_WARN, "clientwr: failed to generate random auth");
2769 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2770 if (!statsrvrq.buf) {
2771 debug(DBG_ERR, "clientwr: malloc failed");
2774 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2775 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2776 sendrq(server, &statsrvrq);
2781 conf->servers = NULL;
2782 if (server->dynamiclookuparg) {
2783 removeserversubrealms(realms, conf);
2787 freeclsrvconf(conf);
2789 freeserver(server, 1);
2790 ERR_remove_state(0);
2794 void *udpserverwr(void *arg) {
2795 struct queue *replyq = udp_server_replyq;
2796 struct reply *reply;
2799 pthread_mutex_lock(&replyq->mutex);
2800 while (!(reply = (struct reply *)list_shift(replyq->entries))) {
2801 debug(DBG_DBG, "udp server writer, waiting for signal");
2802 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2803 debug(DBG_DBG, "udp server writer, got signal");
2805 pthread_mutex_unlock(&replyq->mutex);
2807 if (sendto(reply->toudpsock, reply->buf, RADLEN(reply->buf), 0,
2808 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2809 debug(DBG_WARN, "sendudp: send failed");
2815 void *udpserverrd(void *arg) {
2817 int *sp = (int *)arg;
2820 memset(&rq, 0, sizeof(struct request));
2821 rq.buf = radudpget(*sp, &rq.from, NULL, &rq.fromsa);
2822 rq.fromudpsock = *sp;
2828 void *tlsserverwr(void *arg) {
2830 unsigned long error;
2831 struct client *client = (struct client *)arg;
2832 struct queue *replyq;
2833 struct reply *reply;
2835 debug(DBG_DBG, "tlsserverwr: starting for %s", client->conf->host);
2836 replyq = client->replyq;
2838 pthread_mutex_lock(&replyq->mutex);
2839 while (!list_first(replyq->entries)) {
2841 debug(DBG_DBG, "tlsserverwr: waiting for signal");
2842 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2843 debug(DBG_DBG, "tlsserverwr: got signal");
2846 /* ssl might have changed while waiting */
2847 pthread_mutex_unlock(&replyq->mutex);
2848 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2849 ERR_remove_state(0);
2853 reply = (struct reply *)list_shift(replyq->entries);
2854 pthread_mutex_unlock(&replyq->mutex);
2855 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2857 debug(DBG_DBG, "tlsserverwr: sent %d bytes, Radius packet of length %d",
2858 cnt, RADLEN(reply->buf));
2860 while ((error = ERR_get_error()))
2861 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2867 void tlsserverrd(struct client *client) {
2869 pthread_t tlsserverwrth;
2871 debug(DBG_DBG, "tlsserverrd: starting for %s", client->conf->host);
2873 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2874 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2879 memset(&rq, 0, sizeof(struct request));
2880 rq.buf = radtlsget(client->ssl, 0);
2882 debug(DBG_ERR, "tlsserverrd: connection from %s lost", client->conf->host);
2885 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2888 debug(DBG_ERR, "tlsserverrd: message authentication/validation failed, closing connection from %s", client->conf->host);
2893 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2895 pthread_mutex_lock(&client->replyq->mutex);
2896 pthread_cond_signal(&client->replyq->cond);
2897 pthread_mutex_unlock(&client->replyq->mutex);
2898 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2899 pthread_join(tlsserverwrth, NULL);
2900 removeclientrqs(client);
2901 debug(DBG_DBG, "tlsserverrd: reader for %s exiting", client->conf->host);
2904 void *tlsservernew(void *arg) {
2906 struct sockaddr_storage from;
2907 size_t fromlen = sizeof(from);
2908 struct clsrvconf *conf;
2909 struct list_node *cur = NULL;
2912 unsigned long error;
2913 struct client *client;
2916 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
2917 debug(DBG_DBG, "tlsservernew: getpeername failed, exiting");
2920 debug(DBG_WARN, "tlsservernew: incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2922 conf = find_conf(RAD_TLS, (struct sockaddr *)&from, clconfs, &cur);
2924 ssl = SSL_new(conf->ssl_ctx);
2927 if (SSL_accept(ssl) <= 0) {
2928 while ((error = ERR_get_error()))
2929 debug(DBG_ERR, "tlsservernew: SSL: %s", ERR_error_string(error, NULL));
2930 debug(DBG_ERR, "tlsservernew: SSL_accept failed");
2933 cert = verifytlscert(ssl);
2939 if (verifyconfcert(cert, conf)) {
2941 client = addclient(conf);
2944 tlsserverrd(client);
2945 removeclient(client);
2947 debug(DBG_WARN, "tlsservernew: failed to create new client instance");
2950 conf = find_conf(RAD_TLS, (struct sockaddr *)&from, clconfs, &cur);
2952 debug(DBG_WARN, "tlsservernew: ignoring request, no matching TLS client");
2958 ERR_remove_state(0);
2959 shutdown(s, SHUT_RDWR);
2964 void *tlslistener(void *arg) {
2965 pthread_t tlsserverth;
2966 int s, *sp = (int *)arg;
2967 struct sockaddr_storage from;
2968 size_t fromlen = sizeof(from);
2973 s = accept(*sp, (struct sockaddr *)&from, &fromlen);
2975 debug(DBG_WARN, "accept failed");
2978 if (pthread_create(&tlsserverth, NULL, tlsservernew, (void *)&s)) {
2979 debug(DBG_ERR, "tlslistener: pthread_create failed");
2980 shutdown(s, SHUT_RDWR);
2984 pthread_detach(tlsserverth);
2990 void *tcpserverwr(void *arg) {
2992 struct client *client = (struct client *)arg;
2993 struct queue *replyq;
2994 struct reply *reply;
2996 debug(DBG_DBG, "tcpserverwr: starting for %s", client->conf->host);
2997 replyq = client->replyq;
2999 pthread_mutex_lock(&replyq->mutex);
3000 while (!list_first(replyq->entries)) {
3001 if (client->sock >= 0) {
3002 debug(DBG_DBG, "tcpserverwr: waiting for signal");
3003 pthread_cond_wait(&replyq->cond, &replyq->mutex);
3004 debug(DBG_DBG, "tcpserverwr: got signal");
3006 if (client->sock < 0) {
3007 /* s might have changed while waiting */
3008 pthread_mutex_unlock(&replyq->mutex);
3009 debug(DBG_DBG, "tcpserverwr: exiting as requested");
3013 reply = (struct reply *)list_shift(replyq->entries);
3014 pthread_mutex_unlock(&replyq->mutex);
3015 cnt = write(client->sock, reply->buf, RADLEN(reply->buf));
3017 debug(DBG_DBG, "tcpserverwr: sent %d bytes, Radius packet of length %d",
3018 cnt, RADLEN(reply->buf));
3020 debug(DBG_ERR, "tcpserverwr: write error for %s", client->conf->host);
3026 void tcpserverrd(struct client *client) {
3028 pthread_t tcpserverwrth;
3030 debug(DBG_DBG, "tcpserverrd: starting for %s", client->conf->host);
3032 if (pthread_create(&tcpserverwrth, NULL, tcpserverwr, (void *)client)) {
3033 debug(DBG_ERR, "tcpserverrd: pthread_create failed");
3038 memset(&rq, 0, sizeof(struct request));
3039 rq.buf = radtcpget(client->sock, 0);
3041 debug(DBG_ERR, "tcpserverrd: connection from %s lost", client->conf->host);
3044 debug(DBG_DBG, "tcpserverrd: got Radius message from %s", client->conf->host);
3047 debug(DBG_ERR, "tcpserverrd: message authentication/validation failed, closing connection from %s", client->conf->host);
3052 /* stop writer by setting s to -1 and give signal in case waiting for data */
3054 pthread_mutex_lock(&client->replyq->mutex);
3055 pthread_cond_signal(&client->replyq->cond);
3056 pthread_mutex_unlock(&client->replyq->mutex);
3057 debug(DBG_DBG, "tcpserverrd: waiting for writer to end");
3058 pthread_join(tcpserverwrth, NULL);
3059 removeclientrqs(client);
3060 debug(DBG_DBG, "tcpserverrd: reader for %s exiting", client->conf->host);
3063 void *tcpservernew(void *arg) {
3065 struct sockaddr_storage from;
3066 size_t fromlen = sizeof(from);
3067 struct clsrvconf *conf;
3068 struct client *client;
3071 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
3072 debug(DBG_DBG, "tcpservernew: getpeername failed, exiting");
3075 debug(DBG_WARN, "tcpservernew: incoming TCP connection from %s", addr2string((struct sockaddr *)&from, fromlen));
3077 conf = find_conf(RAD_TCP, (struct sockaddr *)&from, clconfs, NULL);
3079 client = addclient(conf);
3082 tcpserverrd(client);
3083 removeclient(client);
3085 debug(DBG_WARN, "tcpservernew: failed to create new client instance");
3087 debug(DBG_WARN, "tcpservernew: ignoring request, no matching TCP client");
3090 shutdown(s, SHUT_RDWR);
3095 void *tcplistener(void *arg) {
3096 pthread_t tcpserverth;
3097 int s, *sp = (int *)arg;
3098 struct sockaddr_storage from;
3099 size_t fromlen = sizeof(from);
3104 s = accept(*sp, (struct sockaddr *)&from, &fromlen);
3106 debug(DBG_WARN, "accept failed");
3109 if (pthread_create(&tcpserverth, NULL, tcpservernew, (void *)&s)) {
3110 debug(DBG_ERR, "tcplistener: pthread_create failed");
3111 shutdown(s, SHUT_RDWR);
3115 pthread_detach(tcpserverth);
3121 void createlistener(uint8_t type, char *arg) {
3123 struct clsrvconf *listenres;
3124 struct addrinfo *res;
3125 int s = -1, on = 1, *sp = NULL;
3127 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
3129 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
3131 for (res = listenres->addrinfo; res; res = res->ai_next) {
3132 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
3134 debug(DBG_WARN, "createlistener: socket failed");
3137 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
3139 if (res->ai_family == AF_INET6)
3140 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
3142 if (bind(s, res->ai_addr, res->ai_addrlen)) {
3143 debug(DBG_WARN, "createlistener: bind failed");
3149 sp = malloc(sizeof(int));
3151 debugx(1, DBG_ERR, "malloc failed");
3153 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
3154 debugx(1, DBG_ERR, "pthread_create failed");
3158 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
3160 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
3161 listenres->host ? listenres->host : "*", listenres->port);
3162 freeclsrvres(listenres);
3165 void createlisteners(uint8_t type, char **args) {
3169 for (i = 0; args[i]; i++)
3170 createlistener(type, args[i]);
3172 createlistener(type, NULL);
3176 void ssl_info_callback(const SSL *ssl, int where, int ret) {
3180 w = where & ~SSL_ST_MASK;
3182 if (w & SSL_ST_CONNECT)
3184 else if (w & SSL_ST_ACCEPT)
3189 if (where & SSL_CB_LOOP)
3190 debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
3191 else if (where & SSL_CB_ALERT) {
3192 s = (where & SSL_CB_READ) ? "read" : "write";
3193 debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
3195 else if (where & SSL_CB_EXIT) {
3197 debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
3199 debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
3204 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
3205 SSL_CTX *ctx = NULL;
3206 STACK_OF(X509_NAME) *calist;
3209 unsigned long error;
3212 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
3213 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
3214 for (i = 0; i < CRYPTO_num_locks(); i++) {
3215 ssl_lock_count[i] = 0;
3216 pthread_mutex_init(&ssl_locks[i], NULL);
3218 CRYPTO_set_id_callback(ssl_thread_id);
3219 CRYPTO_set_locking_callback(ssl_locking_callback);
3221 SSL_load_error_strings();
3224 while (!RAND_status()) {
3225 time_t t = time(NULL);
3226 pid_t pid = getpid();
3227 RAND_seed((unsigned char *)&t, sizeof(time_t));
3228 RAND_seed((unsigned char *)&pid, sizeof(pid));
3234 ctx = SSL_CTX_new(TLSv1_method());
3236 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
3240 ctx = SSL_CTX_new(DTLSv1_method());
3242 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
3244 SSL_CTX_set_read_ahead(ctx, 1);
3248 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
3252 if (conf->certkeypwd) {
3253 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
3254 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
3256 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
3257 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
3258 !SSL_CTX_check_private_key(ctx) ||
3259 !SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
3260 while ((error = ERR_get_error()))
3261 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
3262 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
3267 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
3268 if (!conf->cacertfile || calist) {
3269 if (conf->cacertpath) {
3271 calist = sk_X509_NAME_new_null();
3272 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
3273 sk_X509_NAME_free(calist);
3279 while ((error = ERR_get_error()))
3280 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
3281 debug(DBG_ERR, "tlscreatectx: Error adding CA subjects in TLS context %s", conf->name);
3285 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
3286 SSL_CTX_set_client_CA_list(ctx, calist);
3288 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
3289 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
3291 if (conf->crlcheck) {
3292 x509_s = SSL_CTX_get_cert_store(ctx);
3293 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
3296 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
3300 SSL_CTX *tlsgetctx(uint8_t type, char *alt1, char *alt2) {
3301 struct list_node *entry;
3302 struct tls *t, *t1 = NULL, *t2 = NULL;
3303 SSL_CTX *ctx = NULL;
3305 pthread_mutex_lock(&tlsconfs_lock);
3307 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
3308 t = (struct tls *)entry->data;
3309 if (!strcasecmp(t->name, alt1)) {
3313 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
3324 t->tlsctx = tlscreatectx(RAD_TLS, t);
3329 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
3335 pthread_mutex_unlock(&tlsconfs_lock);
3339 struct list *addsrvconfs(char *value, char **names) {
3340 struct list *conflist;
3342 struct list_node *entry;
3343 struct clsrvconf *conf = NULL;
3345 if (!names || !*names)
3348 conflist = list_create();
3350 debug(DBG_ERR, "malloc failed");
3354 for (n = 0; names[n]; n++) {
3355 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3356 conf = (struct clsrvconf *)entry->data;
3357 if (!strcasecmp(names[n], conf->name))
3361 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
3362 list_destroy(conflist);
3365 if (!list_push(conflist, conf)) {
3366 debug(DBG_ERR, "malloc failed");
3367 list_destroy(conflist);
3370 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
3375 void freerealm(struct realm *realm) {
3379 free(realm->message);
3380 regfree(&realm->regex);
3381 pthread_mutex_destroy(&realm->subrealms_mutex);
3382 if (realm->subrealms)
3383 list_destroy(realm->subrealms);
3384 if (realm->srvconfs) {
3385 /* emptying list without freeing data */
3386 while (list_shift(realm->srvconfs));
3387 list_destroy(realm->srvconfs);
3389 if (realm->accsrvconfs) {
3390 /* emptying list without freeing data */
3391 while (list_shift(realm->accsrvconfs));
3392 list_destroy(realm->accsrvconfs);
3397 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
3399 struct realm *realm;
3400 char *s, *regex = NULL;
3402 if (*value == '/') {
3403 /* regexp, remove optional trailing / if present */
3404 if (value[strlen(value) - 1] == '/')
3405 value[strlen(value) - 1] = '\0';
3407 /* not a regexp, let us make it one */
3408 if (*value == '*' && !value[1])
3409 regex = stringcopy(".*", 0);
3411 for (n = 0, s = value; *s;)
3414 regex = malloc(strlen(value) + n + 3);
3417 for (n = 1, s = value; *s; s++) {
3427 debug(DBG_ERR, "malloc failed");
3431 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
3434 realm = malloc(sizeof(struct realm));
3436 debug(DBG_ERR, "malloc failed");
3439 memset(realm, 0, sizeof(struct realm));
3441 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
3442 debug(DBG_ERR, "mutex init failed");
3448 realm->name = stringcopy(value, 0);
3450 debug(DBG_ERR, "malloc failed");
3453 if (message && strlen(message) > 253) {
3454 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
3457 realm->message = message;
3458 realm->accresp = accresp;
3460 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
3461 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
3465 if (servers && *servers) {
3466 realm->srvconfs = addsrvconfs(value, servers);
3467 if (!realm->srvconfs)
3471 if (accservers && *accservers) {
3472 realm->accsrvconfs = addsrvconfs(value, accservers);
3473 if (!realm->accsrvconfs)
3477 if (!list_push(realmlist, realm)) {
3478 debug(DBG_ERR, "malloc failed");
3479 pthread_mutex_destroy(&realm->subrealms_mutex);
3483 debug(DBG_DBG, "addrealm: added realm %s", value);
3493 for (n = 0; servers[n]; n++)
3498 for (n = 0; accservers[n]; n++)
3499 free(accservers[n]);
3505 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
3506 struct clsrvconf *srvconf;
3507 struct realm *newrealm = NULL;
3508 char *realmname, *s;
3511 if (!conf->dynamiclookupcommand)
3514 /* create dynamic for the realm (string after last @, exit if nothing after @ */
3515 realmname = strrchr(id, '@');
3521 for (s = realmname; *s; s++)
3522 if (*s != '.' && *s != '-' && !isalnum((int)*s))
3525 pthread_mutex_lock(&realm->subrealms_mutex);
3526 /* exit if we now already got a matching subrealm */
3527 if (id2realm(realm->subrealms, id))
3529 srvconf = malloc(sizeof(struct clsrvconf));
3531 debug(DBG_ERR, "malloc failed");
3535 if (!addserver(srvconf))
3538 if (!realm->subrealms)
3539 realm->subrealms = list_create();
3540 if (!realm->subrealms)
3542 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
3546 /* add server and accserver to newrealm */
3547 newrealm->srvconfs = list_create();
3548 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
3549 debug(DBG_ERR, "malloc failed");
3552 newrealm->accsrvconfs = list_create();
3553 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
3554 debug(DBG_ERR, "malloc failed");
3558 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
3560 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
3561 debug(DBG_ERR, "pthread_create failed");
3564 pthread_detach(clientth);
3569 list_removedata(realm->subrealms, newrealm);
3570 freerealm(newrealm);
3571 if (!list_first(realm->subrealms)) {
3572 list_destroy(realm->subrealms);
3573 realm->subrealms = NULL;
3576 freeserver(srvconf->servers, 1);
3578 debug(DBG_ERR, "failed to create dynamic server");
3581 pthread_mutex_unlock(&realm->subrealms_mutex);
3584 int dynamicconfig(struct server *server) {
3585 int ok, fd[2], status;
3587 struct clsrvconf *conf = server->conf;
3588 struct gconffile *cf = NULL;
3590 /* for now we only learn hostname/address */
3591 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
3594 debug(DBG_ERR, "dynamicconfig: pipe error");
3599 debug(DBG_ERR, "dynamicconfig: fork error");
3603 } else if (pid == 0) {
3606 if (fd[1] != STDOUT_FILENO) {
3607 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
3608 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
3611 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
3612 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
3616 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
3617 ok = getgenericconfig(&cf, NULL,
3618 "Server", CONF_CBK, confserver_cb, (void *)conf,
3623 if (waitpid(pid, &status, 0) < 0) {
3624 debug(DBG_ERR, "dynamicconfig: wait error");
3629 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
3637 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
3641 int addmatchcertattr(struct clsrvconf *conf) {
3645 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
3646 r = &conf->certcnregex;
3647 v = conf->matchcertattr + 4;
3648 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
3649 r = &conf->certuriregex;
3650 v = conf->matchcertattr + 20;
3655 /* regexp, remove optional trailing / if present */
3656 if (v[strlen(v) - 1] == '/')
3657 v[strlen(v) - 1] = '\0';
3661 *r = malloc(sizeof(regex_t));
3663 debug(DBG_ERR, "malloc failed");
3666 if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
3669 debug(DBG_ERR, "failed to compile regular expression %s", v);
3675 int addrewriteattr(struct clsrvconf *conf) {
3678 v = conf->rewriteattr + 11;
3679 if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
3681 /* regexp, remove optional trailing / if present */
3682 if (v[strlen(v) - 1] == '/')
3683 v[strlen(v) - 1] = '\0';
3691 conf->rewriteattrregex = malloc(sizeof(regex_t));
3692 if (!conf->rewriteattrregex) {
3693 debug(DBG_ERR, "malloc failed");
3697 conf->rewriteattrreplacement = stringcopy(w, 0);
3698 if (!conf->rewriteattrreplacement) {
3699 free(conf->rewriteattrregex);
3700 conf->rewriteattrregex = NULL;
3704 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
3705 free(conf->rewriteattrregex);
3706 conf->rewriteattrregex = NULL;
3707 free(conf->rewriteattrreplacement);
3708 conf->rewriteattrreplacement = NULL;
3709 debug(DBG_ERR, "failed to compile regular expression %s", v);
3716 /* should accept both names and numeric values, only numeric right now */
3717 uint8_t attrname2val(char *attrname) {
3720 val = atoi(attrname);
3721 return val > 0 && val < 256 ? val : 0;
3724 /* should accept both names and numeric values, only numeric right now */
3725 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
3728 *vendor = atoi(attrname);
3729 s = strchr(attrname, ':');
3734 *type = atoi(s + 1);
3735 return *type >= 0 && *type < 256;
3738 struct rewrite *getrewrite(char *alt1, char *alt2) {
3739 struct list_node *entry;
3740 struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
3742 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
3743 r = (struct rewriteconf *)entry->data;
3744 if (!strcasecmp(r->name, alt1)) {
3748 if (!r2 && alt2 && !strcasecmp(r->name, alt2))
3758 void addrewrite(char *value, char **attrs, char **vattrs) {
3759 struct rewriteconf *new;
3760 struct rewrite *rewrite = NULL;
3763 uint32_t *p, *va = NULL;
3767 for (; attrs[n]; n++);
3768 a = malloc((n + 1) * sizeof(uint8_t));
3770 debugx(1, DBG_ERR, "malloc failed");
3772 for (i = 0; i < n; i++) {
3773 if (!(a[i] = attrname2val(attrs[i])))
3774 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
3783 for (; vattrs[n]; n++);
3784 va = malloc((2 * n + 1) * sizeof(uint32_t));
3786 debugx(1, DBG_ERR, "malloc failed");
3788 for (p = va, i = 0; i < n; i++, p += 2) {
3789 if (!vattrname2val(vattrs[i], p, p + 1))
3790 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
3798 rewrite = malloc(sizeof(struct rewrite));
3800 debugx(1, DBG_ERR, "malloc failed");
3801 rewrite->removeattrs = a;
3802 rewrite->removevendorattrs = va;
3805 new = malloc(sizeof(struct rewriteconf));
3806 if (!new || !list_push(rewriteconfs, new))
3807 debugx(1, DBG_ERR, "malloc failed");
3809 memset(new, 0, sizeof(struct rewriteconf));
3810 new->name = stringcopy(value, 0);
3812 debugx(1, DBG_ERR, "malloc failed");
3814 new->rewrite = rewrite;
3815 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3818 void freeclsrvconf(struct clsrvconf *conf) {
3824 free(conf->matchcertattr);
3825 if (conf->certcnregex)
3826 regfree(conf->certcnregex);
3827 if (conf->certuriregex)
3828 regfree(conf->certuriregex);
3829 free(conf->confrewrite);
3830 free(conf->rewriteattr);
3831 if (conf->rewriteattrregex)
3832 regfree(conf->rewriteattrregex);
3833 free(conf->rewriteattrreplacement);
3834 free(conf->dynamiclookupcommand);
3835 free(conf->rewrite);
3837 freeaddrinfo(conf->addrinfo);
3838 /* not touching ssl_ctx, clients and servers */
3842 int mergeconfstring(char **dst, char **src) {
3851 t = stringcopy(*dst, 0);
3853 debug(DBG_ERR, "malloc failed");
3861 /* assumes dst is a shallow copy */
3862 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3863 if (!mergeconfstring(&dst->name, &src->name) ||
3864 !mergeconfstring(&dst->host, &src->host) ||
3865 !mergeconfstring(&dst->port, &src->port) ||
3866 !mergeconfstring(&dst->secret, &src->secret) ||
3867 !mergeconfstring(&dst->tls, &src->tls) ||
3868 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3869 !mergeconfstring(&dst->confrewrite, &src->confrewrite) ||
3870 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3873 dst->pdef = src->pdef;
3874 dst->statusserver = src->statusserver;
3875 dst->certnamecheck = src->certnamecheck;
3876 if (src->retryinterval != 255)
3877 dst->retryinterval = src->retryinterval;
3878 if (src->retrycount != 255)
3879 dst->retrycount = src->retrycount;
3883 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3884 struct clsrvconf *conf;
3885 char *conftype = NULL;
3887 debug(DBG_DBG, "confclient_cb called for %s", block);
3889 conf = malloc(sizeof(struct clsrvconf));
3890 if (!conf || !list_push(clconfs, conf))
3891 debugx(1, DBG_ERR, "malloc failed");
3892 memset(conf, 0, sizeof(struct clsrvconf));
3893 conf->certnamecheck = 1;
3895 if (!getgenericconfig(cf, block,
3896 "type", CONF_STR, &conftype,
3897 "host", CONF_STR, &conf->host,
3898 "secret", CONF_STR, &conf->secret,
3899 "tls", CONF_STR, &conf->tls,
3900 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3901 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3902 "rewrite", CONF_STR, &conf->confrewrite,
3903 "rewriteattribute", CONF_STR, &conf->rewriteattr,
3906 debugx(1, DBG_ERR, "configuration error");
3908 conf->name = stringcopy(val, 0);
3910 conf->host = stringcopy(val, 0);
3911 if (!conf->name || !conf->host)
3912 debugx(1, DBG_ERR, "malloc failed");
3915 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3916 conf->type = protoname2int(conftype);
3917 conf->pdef = &protodefs[conf->type];
3918 if (!conf->pdef->name)
3919 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3922 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3923 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultclient", "default");
3925 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3926 if (conf->matchcertattr && !addmatchcertattr(conf))
3927 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3930 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
3932 if (conf->rewriteattr) {
3933 if (!addrewriteattr(conf))
3934 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3937 if (!resolvepeer(conf, 0))
3938 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3940 if (!conf->secret) {
3941 if (!conf->pdef->secretdefault)
3942 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3943 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3945 debugx(1, DBG_ERR, "malloc failed");
3950 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3951 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3952 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultserver", "default");
3953 if (!conf->ssl_ctx) {
3954 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3957 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3958 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3964 conf->port = stringcopy(conf->pdef->portdefault, 0);
3966 debug(DBG_ERR, "malloc failed");
3971 if (conf->retryinterval == 255)
3972 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3973 if (conf->retrycount == 255)
3974 conf->retrycount = protodefs[conf->type].retrycountdefault;
3976 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
3978 if (!conf->secret) {
3979 if (!conf->pdef->secretdefault) {
3980 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3983 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3984 if (!conf->secret) {
3985 debug(DBG_ERR, "malloc failed");
3990 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3991 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3997 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3998 struct clsrvconf *conf, *resconf;
3999 char *conftype = NULL;
4000 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
4002 debug(DBG_DBG, "confserver_cb called for %s", block);
4004 conf = malloc(sizeof(struct clsrvconf));
4006 debug(DBG_ERR, "malloc failed");
4009 memset(conf, 0, sizeof(struct clsrvconf));
4010 resconf = (struct clsrvconf *)arg;
4012 conf->statusserver = resconf->statusserver;
4013 conf->certnamecheck = resconf->certnamecheck;
4015 conf->certnamecheck = 1;
4017 if (!getgenericconfig(cf, block,
4018 "type", CONF_STR, &conftype,
4019 "host", CONF_STR, &conf->host,
4020 "port", CONF_STR, &conf->port,
4021 "secret", CONF_STR, &conf->secret,
4022 "tls", CONF_STR, &conf->tls,
4023 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
4024 "rewrite", CONF_STR, &conf->confrewrite,
4025 "StatusServer", CONF_BLN, &conf->statusserver,
4026 "RetryInterval", CONF_LINT, &retryinterval,
4027 "RetryCount", CONF_LINT, &retrycount,
4028 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
4029 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
4032 debug(DBG_ERR, "configuration error");
4036 conf->name = stringcopy(val, 0);
4038 debug(DBG_ERR, "malloc failed");
4042 conf->host = stringcopy(val, 0);
4044 debug(DBG_ERR, "malloc failed");
4050 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
4051 conf->type = protoname2int(conftype);
4052 conf->pdef = &protodefs[conf->type];
4053 if (!conf->pdef->name) {
4054 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
4060 if (retryinterval != LONG_MIN) {
4061 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
4062 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
4065 conf->retryinterval = (uint8_t)retryinterval;
4067 conf->retryinterval = 255;
4069 if (retrycount != LONG_MIN) {
4070 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
4071 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
4074 conf->retrycount = (uint8_t)retrycount;
4076 conf->retrycount = 255;
4079 if (!mergesrvconf(resconf, conf))
4083 if (conf->dynamiclookupcommand) {
4084 free(conf->dynamiclookupcommand);
4085 conf->dynamiclookupcommand = NULL;
4089 if (resconf || !conf->dynamiclookupcommand) {
4090 if (!compileserverconfig(conf, block))
4097 if (!list_push(srvconfs, conf)) {
4098 debug(DBG_ERR, "malloc failed");
4104 freeclsrvconf(conf);
4108 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4109 char **servers = NULL, **accservers = NULL, *msg = NULL;
4110 uint8_t accresp = 0;
4112 debug(DBG_DBG, "confrealm_cb called for %s", block);
4114 if (!getgenericconfig(cf, block,
4115 "server", CONF_MSTR, &servers,
4116 "accountingServer", CONF_MSTR, &accservers,
4117 "ReplyMessage", CONF_STR, &msg,
4118 "AccountingResponse", CONF_BLN, &accresp,
4121 debugx(1, DBG_ERR, "configuration error");
4123 addrealm(realms, val, servers, accservers, msg, accresp);
4127 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4130 debug(DBG_DBG, "conftls_cb called for %s", block);
4132 conf = malloc(sizeof(struct tls));
4134 debug(DBG_ERR, "conftls_cb: malloc failed");
4137 memset(conf, 0, sizeof(struct tls));
4139 if (!getgenericconfig(cf, block,
4140 "CACertificateFile", CONF_STR, &conf->cacertfile,
4141 "CACertificatePath", CONF_STR, &conf->cacertpath,
4142 "CertificateFile", CONF_STR, &conf->certfile,
4143 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
4144 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
4145 "CRLCheck", CONF_BLN, &conf->crlcheck,
4148 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
4151 if (!conf->certfile || !conf->certkeyfile) {
4152 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
4155 if (!conf->cacertfile && !conf->cacertpath) {
4156 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
4160 conf->name = stringcopy(val, 0);
4162 debug(DBG_ERR, "conftls_cb: malloc failed");
4166 pthread_mutex_lock(&tlsconfs_lock);
4167 if (!list_push(tlsconfs, conf)) {
4168 debug(DBG_ERR, "conftls_cb: malloc failed");
4169 pthread_mutex_unlock(&tlsconfs_lock);
4172 pthread_mutex_unlock(&tlsconfs_lock);
4174 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
4178 free(conf->cacertfile);
4179 free(conf->cacertpath);
4180 free(conf->certfile);
4181 free(conf->certkeyfile);
4182 free(conf->certkeypwd);
4187 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4188 char **attrs = NULL, **vattrs = NULL;
4190 debug(DBG_DBG, "confrewrite_cb called for %s", block);
4192 if (!getgenericconfig(cf, block,
4193 "removeAttribute", CONF_MSTR, &attrs,
4194 "removeVendorAttribute", CONF_MSTR, &vattrs,
4197 debugx(1, DBG_ERR, "configuration error");
4198 addrewrite(val, attrs, vattrs);
4202 void getmainconfig(const char *configfile) {
4203 long int loglevel = LONG_MIN;
4204 struct gconffile *cfs;
4206 cfs = openconfigfile(configfile);
4207 memset(&options, 0, sizeof(options));
4209 clconfs = list_create();
4211 debugx(1, DBG_ERR, "malloc failed");
4213 srvconfs = list_create();
4215 debugx(1, DBG_ERR, "malloc failed");
4217 realms = list_create();
4219 debugx(1, DBG_ERR, "malloc failed");
4221 tlsconfs = list_create();
4223 debugx(1, DBG_ERR, "malloc failed");
4225 rewriteconfs = list_create();
4227 debugx(1, DBG_ERR, "malloc failed");
4229 if (!getgenericconfig(&cfs, NULL,
4230 "ListenUDP", CONF_MSTR, &options.listenudp,
4231 "ListenTCP", CONF_MSTR, &options.listentcp,
4232 "ListenTLS", CONF_MSTR, &options.listentls,
4233 "ListenDTLS", CONF_MSTR, &options.listendtls,
4234 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
4235 "SourceUDP", CONF_STR, &options.sourceudp,
4236 "SourceTCP", CONF_STR, &options.sourcetcp,
4237 "SourceTLS", CONF_STR, &options.sourcetls,
4238 "SourceDTLS", CONF_STR, &options.sourcedtls,
4239 "LogLevel", CONF_LINT, &loglevel,
4240 "LogDestination", CONF_STR, &options.logdestination,
4241 "LoopPrevention", CONF_BLN, &options.loopprevention,
4242 "Client", CONF_CBK, confclient_cb, NULL,
4243 "Server", CONF_CBK, confserver_cb, NULL,
4244 "Realm", CONF_CBK, confrealm_cb, NULL,
4245 "TLS", CONF_CBK, conftls_cb, NULL,
4246 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
4249 debugx(1, DBG_ERR, "configuration error");
4251 if (loglevel != LONG_MIN) {
4252 if (loglevel < 1 || loglevel > 4)
4253 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
4254 options.loglevel = (uint8_t)loglevel;
4258 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
4261 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
4264 *configfile = optarg;
4267 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
4268 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
4269 *loglevel = *optarg - '0';
4278 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
4283 if (!(argc - optind))
4287 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
4291 int daemon(int a, int b) {
4299 for (i = 0; i < 3; i++) {
4301 open("/dev/null", O_RDWR);
4307 void *sighandler(void *arg) {
4312 sigemptyset(&sigset);
4313 sigaddset(&sigset, SIGPIPE);
4314 sigwait(&sigset, &sig);
4315 /* only get SIGPIPE right now, so could simplify below code */
4318 /* completely ignoring this */
4321 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
4324 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
4329 int main(int argc, char **argv) {
4330 pthread_t sigth, udpclient4rdth, udpclient6rdth, udpserverwrth, dtlsclient4rdth, dtlsclient6rdth;
4332 struct list_node *entry;
4333 uint8_t foreground = 0, pretend = 0, loglevel = 0;
4334 char *configfile = NULL;
4335 struct clsrvconf *srvconf;
4337 debug_init("radsecproxy");
4338 debug_set_level(DEBUG_LEVEL);
4339 pthread_mutex_init(&tlsconfs_lock, NULL);
4341 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
4343 debug_set_level(loglevel);
4344 getmainconfig(configfile ? configfile : CONFIG_MAIN);
4346 options.loglevel = loglevel;
4347 else if (options.loglevel)
4348 debug_set_level(options.loglevel);
4350 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
4351 free(options.logdestination);
4353 if (!list_first(clconfs))
4354 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
4355 if (!list_first(realms))
4356 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
4359 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
4361 if (!foreground && (daemon(0, 0) < 0))
4362 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
4364 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
4366 sigemptyset(&sigset);
4367 /* exit on all but SIGPIPE, ignore more? */
4368 sigaddset(&sigset, SIGPIPE);
4369 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
4370 pthread_create(&sigth, NULL, sighandler, NULL);
4372 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
4373 srvconf = (struct clsrvconf *)entry->data;
4374 if (srvconf->dynamiclookupcommand)
4376 if (!addserver(srvconf))
4377 debugx(1, DBG_ERR, "failed to add server");
4378 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
4379 (void *)(srvconf->servers)))
4380 debugx(1, DBG_ERR, "pthread_create failed");
4382 /* srcprotores for UDP no longer needed */
4383 if (srcprotores[RAD_UDP]) {
4384 freeaddrinfo(srcprotores[RAD_UDP]);
4385 srcprotores[RAD_UDP] = NULL;
4388 if (udp_client4_sock >= 0)
4389 if (pthread_create(&udpclient4rdth, NULL, protodefs[RAD_UDP].clientreader, (void *)&udp_client4_sock))
4390 debugx(1, DBG_ERR, "pthread_create failed");
4391 if (udp_client6_sock >= 0)
4392 if (pthread_create(&udpclient6rdth, NULL, protodefs[RAD_UDP].clientreader, (void *)&udp_client6_sock))
4393 debugx(1, DBG_ERR, "pthread_create failed");
4395 if (dtls_client4_sock >= 0)
4396 if (pthread_create(&dtlsclient4rdth, NULL, udpdtlsclientrd, (void *)&dtls_client4_sock))
4397 debugx(1, DBG_ERR, "pthread_create failed");
4398 if (dtls_client6_sock >= 0)
4399 if (pthread_create(&dtlsclient6rdth, NULL, udpdtlsclientrd, (void *)&dtls_client6_sock))
4400 debugx(1, DBG_ERR, "pthread_create failed");
4402 if (find_conf_type(RAD_TCP, clconfs, NULL))
4403 createlisteners(RAD_TCP, options.listentcp);
4405 if (find_conf_type(RAD_TLS, clconfs, NULL))
4406 createlisteners(RAD_TLS, options.listentls);
4408 if (find_conf_type(RAD_DTLS, clconfs, NULL))
4409 createlisteners(RAD_DTLS, options.listendtls);
4411 if (find_conf_type(RAD_UDP, clconfs, NULL)) {
4412 udp_server_replyq = newqueue();
4413 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
4414 debugx(1, DBG_ERR, "pthread_create failed");
4415 createlisteners(RAD_UDP, options.listenudp);
4416 if (options.listenaccudp)
4417 createlisteners(RAD_UDP, options.listenaccudp);
4420 /* just hang around doing nothing, anything to do here? */