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>
67 #include "radsecproxy.h"
73 static struct options options;
74 static struct list *clconfs, *srvconfs;
76 struct hash *tlsconfs, *rewriteconfs;
78 static struct addrinfo *srcprotores[4] = { NULL, NULL, NULL, NULL };
80 static pthread_mutex_t *ssl_locks = NULL;
81 static long *ssl_lock_count;
85 /* minimum required declarations to avoid reordering code */
86 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
87 int dynamicconfig(struct server *server);
88 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
89 void freerealm(struct realm *realm);
90 void freeclsrvconf(struct clsrvconf *conf);
91 void freerqdata(struct request *rq);
93 static const struct protodefs protodefs[] = {
94 { "udp", /* UDP, assuming RAD_UDP defined as 0 */
95 NULL, /* secretdefault */
96 SOCK_DGRAM, /* socktype */
97 "1812", /* portdefault */
98 REQUEST_RETRY_COUNT, /* retrycountdefault */
99 10, /* retrycountmax */
100 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
101 60, /* retryintervalmax */
102 udpserverrd, /* listener */
103 &options.sourceudp, /* srcaddrport */
104 NULL, /* connecter */
105 NULL, /* clientconnreader */
106 clientradputudp, /* clientradput */
107 addclientudp, /* addclient */
108 addserverextraudp, /* addserverextra */
109 initextraudp /* initextra */
111 { "tls", /* TLS, assuming RAD_TLS defined as 1 */
112 "mysecret", /* secretdefault */
113 SOCK_STREAM, /* socktype */
114 "2083", /* portdefault */
115 0, /* retrycountdefault */
116 0, /* retrycountmax */
117 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
118 60, /* retryintervalmax */
119 tlslistener, /* listener */
120 &options.sourcetls, /* srcaddrport */
121 tlsconnect, /* connecter */
122 tlsclientrd, /* clientconnreader */
123 clientradputtls, /* clientradput */
124 NULL, /* addclient */
125 NULL, /* addserverextra */
128 { "tcp", /* TCP, assuming RAD_TCP defined as 2 */
129 NULL, /* secretdefault */
130 SOCK_STREAM, /* socktype */
131 "1812", /* portdefault */
132 0, /* retrycountdefault */
133 0, /* retrycountmax */
134 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
135 60, /* retryintervalmax */
136 tcplistener, /* listener */
137 &options.sourcetcp, /* srcaddrport */
138 tcpconnect, /* connecter */
139 tcpclientrd, /* clientconnreader */
140 clientradputtcp, /* clientradput */
141 NULL, /* addclient */
142 NULL, /* addserverextra */
145 { "dtls", /* DTLS, assuming RAD_DTLS defined as 3 */
146 "mysecret", /* secretdefault */
147 SOCK_DGRAM, /* socktype */
148 "2083", /* portdefault */
149 REQUEST_RETRY_COUNT, /* retrycountdefault */
150 10, /* retrycountmax */
151 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
152 60, /* retryintervalmax */
153 udpdtlsserverrd, /* listener */
154 &options.sourcedtls, /* srcaddrport */
155 dtlsconnect, /* connecter */
156 dtlsclientrd, /* clientconnreader */
157 clientradputdtls, /* clientradput */
158 NULL, /* addclient */
159 addserverextradtls, /* addserverextra */
160 initextradtls /* initextra */
166 uint8_t protoname2int(const char *name) {
169 for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
173 /* callbacks for making OpenSSL thread safe */
174 unsigned long ssl_thread_id() {
175 return (unsigned long)pthread_self();
178 void ssl_locking_callback(int mode, int type, const char *file, int line) {
179 if (mode & CRYPTO_LOCK) {
180 pthread_mutex_lock(&ssl_locks[type]);
181 ssl_lock_count[type]++;
183 pthread_mutex_unlock(&ssl_locks[type]);
186 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
187 int pwdlen = strlen(userdata);
188 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
190 memcpy(buf, userdata, pwdlen);
194 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
199 err_cert = X509_STORE_CTX_get_current_cert(ctx);
200 err = X509_STORE_CTX_get_error(ctx);
201 depth = X509_STORE_CTX_get_error_depth(ctx);
203 if (depth > MAX_CERT_DEPTH) {
205 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
206 X509_STORE_CTX_set_error(ctx, err);
210 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
211 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
214 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
215 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
216 debug(DBG_WARN, "\tIssuer=%s", buf);
218 case X509_V_ERR_CERT_NOT_YET_VALID:
219 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
220 debug(DBG_WARN, "\tCertificate not yet valid");
222 case X509_V_ERR_CERT_HAS_EXPIRED:
223 debug(DBG_WARN, "Certificate has expired");
225 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
226 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
231 printf("certificate verify returns %d\n", ok);
236 struct addrinfo *getsrcprotores(uint8_t type) {
237 return srcprotores[type];
240 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
241 struct addrinfo hints, *addrinfo, *res;
245 slash = conf->host ? strchr(conf->host, '/') : NULL;
249 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
253 if (*s < '0' || *s > '9') {
254 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
257 plen = atoi(slash + 1);
258 if (plen < 0 || plen > 128) {
259 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
264 memset(&hints, 0, sizeof(hints));
265 hints.ai_socktype = conf->pdef->socktype;
266 hints.ai_family = AF_UNSPEC;
267 hints.ai_flags = ai_flags;
268 if (!conf->host && !conf->port) {
269 /* getaddrinfo() doesn't like host and port to be NULL */
270 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
271 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
274 for (res = addrinfo; res; res = res->ai_next) {
275 switch (res->ai_family) {
277 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
280 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
286 hints.ai_flags |= AI_NUMERICHOST;
287 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
288 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
293 switch (addrinfo->ai_family) {
296 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
297 freeaddrinfo(addrinfo);
304 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
305 freeaddrinfo(addrinfo);
308 conf->prefixlen = plen;
310 conf->prefixlen = 255;
313 freeaddrinfo(conf->addrinfo);
314 conf->addrinfo = addrinfo;
318 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
323 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
327 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
329 debugx(1, DBG_ERR, "no ] matching initial [");
333 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
336 debugx(1, DBG_ERR, "missing host/address");
338 conf->host = stringcopy(field, p - field);
341 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
342 debugx(1, DBG_ERR, "unexpected character after ]");
345 /* port number or service name is specified */;
347 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
349 debugx(1, DBG_ERR, "syntax error, : but no following port");
350 conf->port = stringcopy(field, p - field);
352 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
356 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
357 struct clsrvconf *conf;
359 conf = malloc(sizeof(struct clsrvconf));
361 debugx(1, DBG_ERR, "malloc failed");
362 memset(conf, 0, sizeof(struct clsrvconf));
364 conf->pdef = &protodefs[conf->type];
366 parsehostport(lconf, conf, default_port);
367 if (!strcmp(conf->host, "*")) {
372 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
373 if (!resolvepeer(conf, AI_PASSIVE))
374 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
378 void freeclsrvres(struct clsrvconf *res) {
382 freeaddrinfo(res->addrinfo);
386 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
388 struct addrinfo *res;
390 for (res = addrinfo; res; res = res->ai_next) {
391 if (family != AF_UNSPEC && family != res->ai_family)
393 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
395 debug(DBG_WARN, "bindtoaddr: socket failed");
399 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
402 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
404 if (!bind(s, res->ai_addr, res->ai_addrlen))
406 debug(DBG_WARN, "bindtoaddr: bind failed");
412 int connecttcp(struct addrinfo *addrinfo, struct addrinfo *src) {
414 struct addrinfo *res;
417 for (res = addrinfo; res; res = res->ai_next) {
418 s = bindtoaddr(src, res->ai_family, 1, 1);
420 debug(DBG_WARN, "connecttoserver: socket failed");
423 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
425 debug(DBG_WARN, "connecttoserver: connect failed");
432 /* returns 1 if the len first bits are equal, else 0 */
433 int prefixmatch(void *a1, void *a2, uint8_t len) {
434 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
436 if (l && memcmp(a1, a2, l))
441 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
444 /* returns next config with matching address, or NULL */
445 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
446 struct sockaddr_in6 *sa6 = NULL;
447 struct in_addr *a4 = NULL;
448 struct addrinfo *res;
449 struct list_node *entry;
450 struct clsrvconf *conf;
452 if (addr->sa_family == AF_INET6) {
453 sa6 = (struct sockaddr_in6 *)addr;
454 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
455 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
459 a4 = &((struct sockaddr_in *)addr)->sin_addr;
461 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
462 conf = (struct clsrvconf *)entry->data;
463 if (conf->type == type) {
464 if (conf->prefixlen == 255) {
465 for (res = conf->addrinfo; res; res = res->ai_next)
466 if ((a4 && res->ai_family == AF_INET &&
467 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
468 (sa6 && res->ai_family == AF_INET6 &&
469 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
475 res = conf->addrinfo;
477 ((a4 && res->ai_family == AF_INET &&
478 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
479 (sa6 && res->ai_family == AF_INET6 &&
480 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
491 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
492 return find_conf(type, addr, clconfs, cur);
495 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
496 return find_conf(type, addr, srvconfs, cur);
499 /* returns next config of given type, or NULL */
500 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
501 struct list_node *entry;
502 struct clsrvconf *conf;
504 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
505 conf = (struct clsrvconf *)entry->data;
506 if (conf->type == type) {
515 struct queue *newqueue() {
518 q = malloc(sizeof(struct queue));
520 debugx(1, DBG_ERR, "malloc failed");
521 q->entries = list_create();
523 debugx(1, DBG_ERR, "malloc failed");
524 pthread_mutex_init(&q->mutex, NULL);
525 pthread_cond_init(&q->cond, NULL);
529 void removequeue(struct queue *q) {
530 struct list_node *entry;
534 pthread_mutex_lock(&q->mutex);
535 for (entry = list_first(q->entries); entry; entry = list_next(entry))
536 free(((struct reply *)entry)->buf);
537 list_destroy(q->entries);
538 pthread_cond_destroy(&q->cond);
539 pthread_mutex_unlock(&q->mutex);
540 pthread_mutex_destroy(&q->mutex);
544 void freebios(struct queue *q) {
547 pthread_mutex_lock(&q->mutex);
548 while ((bio = (BIO *)list_shift(q->entries)))
550 pthread_mutex_unlock(&q->mutex);
554 struct client *addclient(struct clsrvconf *conf) {
555 struct client *new = malloc(sizeof(struct client));
558 debug(DBG_ERR, "malloc failed");
561 if (!conf->clients) {
562 conf->clients = list_create();
563 if (!conf->clients) {
564 debug(DBG_ERR, "malloc failed");
569 memset(new, 0, sizeof(struct client));
571 if (conf->pdef->addclient)
572 conf->pdef->addclient(new);
574 new->replyq = newqueue();
575 list_push(conf->clients, new);
579 void removeclient(struct client *client) {
580 if (!client || !client->conf->clients)
582 removequeue(client->replyq);
583 list_removedata(client->conf->clients, client);
587 void removeclientrqs(struct client *client) {
588 struct list_node *entry;
589 struct server *server;
593 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
594 server = ((struct clsrvconf *)entry->data)->servers;
597 pthread_mutex_lock(&server->newrq_mutex);
598 for (i = 0; i < MAX_REQUESTS; i++) {
599 rq = server->requests + i;
600 if (rq->from == client)
603 pthread_mutex_unlock(&server->newrq_mutex);
607 void freeserver(struct server *server, uint8_t destroymutex) {
608 struct request *rq, *end;
613 if (server->requests) {
614 rq = server->requests;
615 for (end = rq + MAX_REQUESTS; rq < end; rq++)
617 free(server->requests);
620 freebios(server->rbios);
621 free(server->dynamiclookuparg);
623 SSL_free(server->ssl);
625 pthread_mutex_destroy(&server->lock);
626 pthread_cond_destroy(&server->newrq_cond);
627 pthread_mutex_destroy(&server->newrq_mutex);
632 int addserver(struct clsrvconf *conf) {
633 struct clsrvconf *res;
637 debug(DBG_ERR, "addserver: currently works with just one server per conf");
640 conf->servers = malloc(sizeof(struct server));
641 if (!conf->servers) {
642 debug(DBG_ERR, "malloc failed");
645 memset(conf->servers, 0, sizeof(struct server));
646 conf->servers->conf = conf;
649 if (type == RAD_DTLS)
650 conf->servers->rbios = newqueue();
652 if (!srcprotores[type]) {
653 res = resolve_hostport(type, *conf->pdef->srcaddrport, NULL);
654 srcprotores[type] = res->addrinfo;
655 res->addrinfo = NULL;
659 conf->servers->sock = -1;
660 if (conf->pdef->addserverextra)
661 conf->pdef->addserverextra(conf);
663 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
664 if (!conf->servers->requests) {
665 debug(DBG_ERR, "malloc failed");
668 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
669 debug(DBG_ERR, "mutex init failed");
672 conf->servers->newrq = 0;
673 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
674 debug(DBG_ERR, "mutex init failed");
675 pthread_mutex_destroy(&conf->servers->lock);
678 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
679 debug(DBG_ERR, "mutex init failed");
680 pthread_mutex_destroy(&conf->servers->newrq_mutex);
681 pthread_mutex_destroy(&conf->servers->lock);
688 freeserver(conf->servers, 0);
689 conf->servers = NULL;
693 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
694 int loc, i, l, n, r = 0;
697 STACK_OF(GENERAL_NAME) *alt;
700 debug(DBG_DBG, "subjectaltnameaddr");
702 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
706 ex = X509_get_ext(cert, loc);
707 alt = X509V3_EXT_d2i(ex);
711 n = sk_GENERAL_NAME_num(alt);
712 for (i = 0; i < n; i++) {
713 gn = sk_GENERAL_NAME_value(alt, i);
714 if (gn->type != GEN_IPADD)
717 v = (char *)ASN1_STRING_data(gn->d.ia5);
718 l = ASN1_STRING_length(gn->d.ia5);
719 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
720 && !memcmp(v, &addr, l)) {
725 GENERAL_NAMES_free(alt);
729 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
736 nm = X509_get_subject_name(cert);
739 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
742 e = X509_NAME_get_entry(nm, loc);
743 t = X509_NAME_ENTRY_get_data(e);
744 v = (char *) ASN1_STRING_data(t);
745 l = ASN1_STRING_length(t);
749 if (l == strlen(exact) && !strncasecmp(exact, v, l))
752 s = stringcopy((char *)v, l);
754 debug(DBG_ERR, "malloc failed");
757 if (regexec(regex, s, 0, NULL, 0)) {
768 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
769 int loc, i, l, n, r = 0;
772 STACK_OF(GENERAL_NAME) *alt;
775 debug(DBG_DBG, "subjectaltnameregexp");
777 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
781 ex = X509_get_ext(cert, loc);
782 alt = X509V3_EXT_d2i(ex);
786 n = sk_GENERAL_NAME_num(alt);
787 for (i = 0; i < n; i++) {
788 gn = sk_GENERAL_NAME_value(alt, i);
789 if (gn->type != type)
792 v = (char *)ASN1_STRING_data(gn->d.ia5);
793 l = ASN1_STRING_length(gn->d.ia5);
797 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
800 if (memcmp(v, exact, l))
803 s = stringcopy((char *)v, l);
805 debug(DBG_ERR, "malloc failed");
808 if (regexec(regex, s, 0, NULL, 0)) {
817 GENERAL_NAMES_free(alt);
821 X509 *verifytlscert(SSL *ssl) {
825 if (SSL_get_verify_result(ssl) != X509_V_OK) {
826 debug(DBG_ERR, "verifytlscert: basic validation failed");
827 while ((error = ERR_get_error()))
828 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
832 cert = SSL_get_peer_certificate(ssl);
834 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
838 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
840 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
841 struct in6_addr addr;
843 if (conf->certnamecheck && conf->prefixlen == 255) {
844 if (inet_pton(AF_INET, conf->host, &addr))
846 else if (inet_pton(AF_INET6, conf->host, &addr))
849 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
852 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
855 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
857 if (!cnregexp(cert, conf->host, NULL)) {
858 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
861 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
864 if (conf->certcnregex) {
865 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
866 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
869 debug(DBG_DBG, "verifyconfcert: CN matching regex");
871 if (conf->certuriregex) {
872 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
873 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
876 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
881 int radsign(unsigned char *rad, unsigned char *sec) {
882 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
883 static unsigned char first = 1;
884 static EVP_MD_CTX mdctx;
888 pthread_mutex_lock(&lock);
890 EVP_MD_CTX_init(&mdctx);
894 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
895 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
896 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
897 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
899 pthread_mutex_unlock(&lock);
903 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
904 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
905 static unsigned char first = 1;
906 static EVP_MD_CTX mdctx;
907 unsigned char hash[EVP_MAX_MD_SIZE];
911 pthread_mutex_lock(&lock);
913 EVP_MD_CTX_init(&mdctx);
919 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
920 EVP_DigestUpdate(&mdctx, rad, 4) &&
921 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
922 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
923 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
924 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
926 !memcmp(hash, rad + 4, 16));
927 pthread_mutex_unlock(&lock);
931 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
932 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
933 static unsigned char first = 1;
934 static HMAC_CTX hmacctx;
936 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
938 pthread_mutex_lock(&lock);
940 HMAC_CTX_init(&hmacctx);
944 memcpy(auth, authattr, 16);
945 memset(authattr, 0, 16);
947 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
948 HMAC_Update(&hmacctx, rad, RADLEN(rad));
949 HMAC_Final(&hmacctx, hash, &md_len);
950 memcpy(authattr, auth, 16);
952 debug(DBG_WARN, "message auth computation failed");
953 pthread_mutex_unlock(&lock);
957 if (memcmp(auth, hash, 16)) {
958 debug(DBG_WARN, "message authenticator, wrong value");
959 pthread_mutex_unlock(&lock);
963 pthread_mutex_unlock(&lock);
967 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
968 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
969 static unsigned char first = 1;
970 static HMAC_CTX hmacctx;
976 pthread_mutex_lock(&lock);
978 HMAC_CTX_init(&hmacctx);
982 memset(authattrval, 0, 16);
984 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
985 HMAC_Update(&hmacctx, rad, RADLEN(rad));
986 HMAC_Final(&hmacctx, authattrval, &md_len);
988 debug(DBG_WARN, "message auth computation failed");
989 pthread_mutex_unlock(&lock);
993 pthread_mutex_unlock(&lock);
997 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
999 if (ATTRTYPE(attrs) == type)
1001 length -= ATTRLEN(attrs);
1002 attrs += ATTRLEN(attrs);
1007 void freerqdata(struct request *rq) {
1008 if (rq->origusername)
1009 free(rq->origusername);
1014 void sendrq(struct server *to, struct request *rq) {
1018 pthread_mutex_lock(&to->newrq_mutex);
1019 /* might simplify if only try nextid, might be ok */
1020 for (i = to->nextid; i < MAX_REQUESTS; i++)
1021 if (!to->requests[i].buf)
1023 if (i == MAX_REQUESTS) {
1024 for (i = 0; i < to->nextid; i++)
1025 if (!to->requests[i].buf)
1027 if (i == to->nextid) {
1028 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
1034 rq->buf[1] = (char)i;
1036 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1037 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1042 if (*rq->buf == RAD_Accounting_Request) {
1043 if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
1044 debug(DBG_WARN, "sendrq: failed to sign Accounting-Request message");
1050 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1051 to->requests[i] = *rq;
1056 debug(DBG_DBG, "sendrq: signalling client writer");
1057 pthread_cond_signal(&to->newrq_cond);
1060 pthread_mutex_unlock(&to->newrq_mutex);
1063 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa, int toudpsock) {
1064 struct reply *reply;
1067 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1069 debug(DBG_WARN, "sendreply: failed to sign message");
1073 reply = malloc(sizeof(struct reply));
1076 debug(DBG_ERR, "sendreply: malloc failed");
1079 memset(reply, 0, sizeof(struct reply));
1082 reply->tosa = *tosa;
1083 reply->toudpsock = toudpsock;
1085 pthread_mutex_lock(&to->replyq->mutex);
1087 first = list_first(to->replyq->entries) == NULL;
1089 if (!list_push(to->replyq->entries, reply)) {
1090 pthread_mutex_unlock(&to->replyq->mutex);
1093 debug(DBG_ERR, "sendreply: malloc failed");
1098 debug(DBG_DBG, "signalling server writer");
1099 pthread_cond_signal(&to->replyq->cond);
1101 pthread_mutex_unlock(&to->replyq->mutex);
1104 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1105 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1106 static unsigned char first = 1;
1107 static EVP_MD_CTX mdctx;
1108 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1109 unsigned int md_len;
1110 uint8_t i, offset = 0, out[128];
1112 pthread_mutex_lock(&lock);
1114 EVP_MD_CTX_init(&mdctx);
1120 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1121 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1122 !EVP_DigestUpdate(&mdctx, input, 16) ||
1123 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1125 pthread_mutex_unlock(&lock);
1128 for (i = 0; i < 16; i++)
1129 out[offset + i] = hash[i] ^ in[offset + i];
1130 input = out + offset - 16;
1135 memcpy(in, out, len);
1136 pthread_mutex_unlock(&lock);
1140 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1141 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1142 static unsigned char first = 1;
1143 static EVP_MD_CTX mdctx;
1144 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1145 unsigned int md_len;
1146 uint8_t i, offset = 0, out[128];
1148 pthread_mutex_lock(&lock);
1150 EVP_MD_CTX_init(&mdctx);
1156 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1157 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1158 !EVP_DigestUpdate(&mdctx, input, 16) ||
1159 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1161 pthread_mutex_unlock(&lock);
1164 for (i = 0; i < 16; i++)
1165 out[offset + i] = hash[i] ^ in[offset + i];
1166 input = in + offset;
1171 memcpy(in, out, len);
1172 pthread_mutex_unlock(&lock);
1176 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1177 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1178 static unsigned char first = 1;
1179 static EVP_MD_CTX mdctx;
1180 unsigned char hash[EVP_MAX_MD_SIZE];
1181 unsigned int md_len;
1184 pthread_mutex_lock(&lock);
1186 EVP_MD_CTX_init(&mdctx);
1191 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1192 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1193 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1196 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1197 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1198 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1199 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1200 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1201 pthread_mutex_unlock(&lock);
1206 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1209 for (i = 0; i < 16; i++)
1212 for (offset = 16; offset < len; offset += 16) {
1214 printf("text + offset - 16 c(%d): ", offset / 16);
1215 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1217 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1218 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1219 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1220 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1222 pthread_mutex_unlock(&lock);
1226 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1229 for (i = 0; i < 16; i++)
1230 text[offset + i] ^= hash[i];
1234 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1237 pthread_mutex_unlock(&lock);
1241 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1242 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1243 static unsigned char first = 1;
1244 static EVP_MD_CTX mdctx;
1245 unsigned char hash[EVP_MAX_MD_SIZE];
1246 unsigned int md_len;
1250 pthread_mutex_lock(&lock);
1252 EVP_MD_CTX_init(&mdctx);
1257 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1258 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1259 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1262 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1263 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1264 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1265 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1266 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1267 pthread_mutex_unlock(&lock);
1272 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1275 for (i = 0; i < 16; i++)
1276 plain[i] = text[i] ^ hash[i];
1278 for (offset = 16; offset < len; offset += 16) {
1280 printf("text + offset - 16 c(%d): ", offset / 16);
1281 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1283 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1284 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1285 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1286 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1288 pthread_mutex_unlock(&lock);
1292 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1295 for (i = 0; i < 16; i++)
1296 plain[offset + i] = text[offset + i] ^ hash[i];
1299 memcpy(text, plain, len);
1301 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1304 pthread_mutex_unlock(&lock);
1308 struct realm *id2realm(struct list *realmlist, char *id) {
1309 struct list_node *entry;
1310 struct realm *realm, *subrealm = NULL;
1312 /* need to do locking for subrealms and check subrealm timers */
1313 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1314 realm = (struct realm *)entry->data;
1315 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1316 pthread_mutex_lock(&realm->subrealms_mutex);
1317 if (realm->subrealms)
1318 subrealm = id2realm(realm->subrealms, id);
1319 pthread_mutex_unlock(&realm->subrealms_mutex);
1320 return subrealm ? subrealm : realm;
1326 /* helper function, only used by removeserversubrealms() */
1327 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1328 struct list_node *entry;
1329 struct realm *realm;
1331 for (entry = list_first(realmlist); entry;) {
1332 realm = (struct realm *)entry->data;
1333 entry = list_next(entry);
1334 if (realm->srvconfs) {
1335 list_removedata(realm->srvconfs, srv);
1336 if (!list_first(realm->srvconfs)) {
1337 list_destroy(realm->srvconfs);
1338 realm->srvconfs = NULL;
1341 if (realm->accsrvconfs) {
1342 list_removedata(realm->accsrvconfs, srv);
1343 if (!list_first(realm->accsrvconfs)) {
1344 list_destroy(realm->accsrvconfs);
1345 realm->accsrvconfs = NULL;
1349 /* remove subrealm if no servers */
1350 if (!realm->srvconfs && !realm->accsrvconfs) {
1351 list_removedata(realmlist, realm);
1357 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1358 struct list_node *entry;
1359 struct realm *realm;
1361 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1362 realm = (struct realm *)entry->data;
1363 pthread_mutex_lock(&realm->subrealms_mutex);
1364 if (realm->subrealms) {
1365 _internal_removeserversubrealms(realm->subrealms, srv);
1366 if (!list_first(realm->subrealms)) {
1367 list_destroy(realm->subrealms);
1368 realm->subrealms = NULL;
1371 pthread_mutex_unlock(&realm->subrealms_mutex);
1375 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1376 struct request *rq = to->requests, *end;
1378 pthread_mutex_lock(&to->newrq_mutex);
1379 for (end = rq + MAX_REQUESTS; rq < end; rq++)
1380 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1382 pthread_mutex_unlock(&to->newrq_mutex);
1387 int attrvalidate(unsigned char *attrs, int length) {
1388 while (length > 1) {
1389 if (ATTRLEN(attrs) < 2) {
1390 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1393 length -= ATTRLEN(attrs);
1395 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1398 attrs += ATTRLEN(attrs);
1401 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1405 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1406 if (len < 16 || len > 128 || len % 16) {
1407 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1411 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1412 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1416 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1418 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1419 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1425 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1428 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1429 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1432 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1433 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1439 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1440 char *oldsecret, char *newsecret) {
1441 unsigned char *attr;
1443 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1444 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1445 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1451 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1455 for (; attrs[0]; attrs += 2)
1456 if (attrs[0] == vendor && attrs[1] == subattr)
1461 int dovendorrewriterm(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1462 uint8_t alen, sublen, rmlen = 0;
1463 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1466 if (!removevendorattrs)
1469 while (*removevendorattrs && *removevendorattrs != vendor)
1470 removevendorattrs += 2;
1471 if (!*removevendorattrs)
1474 alen = ATTRLEN(attrs);
1476 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1477 /* remove entire vendor attribute */
1478 memmove(attrs, attrs + alen, length - alen);
1483 subattrs = ATTRVAL(attrs) + 4;
1485 if (!attrvalidate(subattrs, sublen)) {
1486 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1491 while (sublen > 1) {
1492 alen = ATTRLEN(subattrs);
1495 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1496 memmove(subattrs, subattrs + alen, length);
1502 ATTRLEN(attrs) -= rmlen;
1506 void dorewriterm(uint8_t *buf, uint8_t *rmattrs, uint32_t *rmvattrs) {
1507 uint8_t *attrs, alen;
1508 uint16_t len, rmlen = 0;
1510 len = RADLEN(buf) - 20;
1513 alen = ATTRLEN(attrs);
1515 if (rmattrs && strchr((char *)rmattrs, ATTRTYPE(attrs))) {
1516 memmove(attrs, attrs + alen, len);
1518 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rmvattrs)
1519 rmlen += dovendorrewriterm(attrs, len, rmvattrs);
1524 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1527 int dorewriteadd(uint8_t **buf, struct list *addattrs) {
1528 struct list_node *n;
1529 struct attribute *a;
1530 uint16_t i, addlen = 0;
1533 for (n = list_first(addattrs); n; n = list_next(n))
1534 addlen += 2 + ((struct attribute *)n->data)->l;
1537 newbuf = realloc(*buf, RADLEN(*buf) + addlen);
1542 for (n = list_first(addattrs); n; n = list_next(n)) {
1543 a = (struct attribute *)n->data;
1545 newbuf[i++] = a->l + 2;
1546 memcpy(newbuf + i, a->v, a->l);
1549 ((uint16_t *)newbuf)[1] = htons(RADLEN(newbuf) + addlen);
1554 /* returns a pointer to the resized attribute value */
1555 uint8_t *resizeattr(uint8_t **buf, uint8_t **attr, uint8_t newvallen) {
1560 vallen = ATTRVALLEN(*attr);
1561 if (vallen == newvallen)
1564 len = RADLEN(*buf) + newvallen - vallen;
1566 if (newvallen > vallen) {
1567 new = realloc(*buf, len);
1569 debug(DBG_ERR, "resizeattr: malloc failed");
1573 *attr += new - *buf;
1577 memmove(*attr + 2 + newvallen, *attr + 2 + vallen, len - (*attr - *buf + newvallen));
1578 (*attr)[1] = newvallen + 2;
1579 ((uint16_t *)*buf)[1] = htons(len);
1583 int dorewritemodattr(uint8_t **buf, uint8_t **attr, struct modattr *modattr) {
1584 size_t nmatch = 10, reslen = 0, start = 0;
1585 regmatch_t pmatch[10], *pfield;
1587 unsigned char *result;
1590 in = stringcopy((char *)ATTRVAL(*attr), ATTRVALLEN(*attr));
1594 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1599 out = modattr->replacement;
1601 for (i = start; out[i]; i++) {
1602 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1603 pfield = &pmatch[out[i + 1] - '0'];
1604 if (pfield->rm_so >= 0) {
1605 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1611 reslen += i - start;
1613 debug(DBG_WARN, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1617 result = resizeattr(buf, attr, reslen);
1625 for (i = start; out[i]; i++) {
1626 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1627 pfield = &pmatch[out[i + 1] - '0'];
1628 if (pfield->rm_so >= 0) {
1629 memcpy(result + reslen, out + start, i - start);
1630 reslen += i - start;
1631 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1632 reslen += pfield->rm_eo - pfield->rm_so;
1639 memcpy(result + reslen, out + start, i - start);
1643 int dorewritemod(uint8_t **buf, struct list *modattrs) {
1646 struct list_node *n;
1649 while (RADLEN(*buf) - 22 >= len) {
1650 for (n = list_first(modattrs); n; n = list_next(n))
1651 if (ATTRTYPE(attr) == ((struct modattr *)n->data)->t)
1652 if (!dorewritemodattr(buf, &attr, (struct modattr *)n->data))
1654 len += ATTRLEN(attr);
1655 attr += ATTRLEN(attr);
1660 int dorewrite(uint8_t **buf, struct rewrite *rewrite) {
1663 if (rewrite->removeattrs || rewrite->removevendorattrs)
1664 dorewriterm(*buf, rewrite->removeattrs, rewrite->removevendorattrs);
1665 if (rewrite->addattrs && !dorewriteadd(buf, rewrite->addattrs))
1667 if (rewrite->modattrs && !dorewritemod(buf, rewrite->modattrs))
1672 int rewriteusername(struct request *rq, uint8_t *attr, char *in) {
1673 if (!dorewritemodattr(&rq->buf, &attr, rq->from->conf->rewriteusername))
1675 if (strlen(in) == ATTRVALLEN(attr) && !memcmp(in, ATTRVAL(attr), ATTRVALLEN(attr)))
1678 rq->origusername = stringcopy(in, 0);
1679 if (!rq->origusername)
1682 memcpy(in, ATTRVAL(attr), ATTRVALLEN(attr));
1683 in[ATTRVALLEN(attr)] = '\0';
1687 const char *radmsgtype2string(uint8_t code) {
1688 static const char *rad_msg_names[] = {
1689 "", "Access-Request", "Access-Accept", "Access-Reject",
1690 "Accounting-Request", "Accounting-Response", "", "",
1691 "", "", "", "Access-Challenge",
1692 "Status-Server", "Status-Client"
1694 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1697 void char2hex(char *h, unsigned char c) {
1698 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1699 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1700 h[0] = hexdigits[c / 16];
1701 h[1] = hexdigits[c % 16];
1705 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
1709 if (!attr || len == 1) {
1714 l = ATTRVALLEN(attr);
1715 s = (char *)ATTRVAL(attr);
1718 for (i = 0; i < l; i++) {
1719 if (s[i] > 31 && s[i] < 127) {
1721 if (d - ascii == len - 1)
1724 if (d - ascii > len - 4)
1729 if (d - ascii == len - 1)
1737 void acclog(unsigned char *attrs, int length, char *host) {
1738 unsigned char *attr;
1741 attr = attrget(attrs, length, RAD_Attr_User_Name);
1743 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1746 radattr2ascii(username, sizeof(username), attr);
1747 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1750 void respondaccounting(struct request *rq) {
1751 unsigned char *resp;
1755 debug(DBG_ERR, "respondaccounting: malloc failed");
1758 memcpy(resp, rq->buf, 20);
1759 resp[0] = RAD_Accounting_Response;
1762 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1763 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1766 void respondstatusserver(struct request *rq) {
1767 unsigned char *resp;
1771 debug(DBG_ERR, "respondstatusserver: malloc failed");
1774 memcpy(resp, rq->buf, 20);
1775 resp[0] = RAD_Access_Accept;
1778 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1779 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1782 void respondreject(struct request *rq, char *message) {
1783 unsigned char *resp;
1786 if (message && *message)
1787 len += 2 + strlen(message);
1791 debug(DBG_ERR, "respondreject: malloc failed");
1794 memcpy(resp, rq->buf, 20);
1795 resp[0] = RAD_Access_Reject;
1796 *(uint16_t *)(resp + 2) = htons(len);
1797 if (message && *message) {
1798 resp[20] = RAD_Attr_Reply_Message;
1799 resp[21] = len - 20;
1800 memcpy(resp + 22, message, len - 22);
1802 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1805 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1806 struct list_node *entry;
1807 struct clsrvconf *server, *best = NULL, *first = NULL;
1809 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1810 server = (struct clsrvconf *)entry->data;
1811 if (!server->servers)
1815 if (!server->servers->connectionok)
1817 if (!server->servers->lostrqs)
1823 if (server->servers->lostrqs < best->servers->lostrqs)
1826 return best ? best : first;
1829 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
1830 struct clsrvconf *srvconf;
1832 *realm = id2realm(realms, id);
1835 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1836 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1839 if (!acc && !srvconf->servers)
1840 adddynamicrealmserver(*realm, srvconf, id);
1841 return srvconf->servers;
1844 /* returns 0 if validation/authentication fails, else 1 */
1845 int radsrv(struct request *rq) {
1846 uint8_t code, id, *auth, *attrs, *attr;
1848 struct server *to = NULL;
1849 char username[254], userascii[760];
1850 unsigned char newauth[16];
1851 struct realm *realm = NULL;
1853 code = *(uint8_t *)rq->buf;
1854 id = *(uint8_t *)(rq->buf + 1);
1855 len = RADLEN(rq->buf);
1856 auth = (uint8_t *)(rq->buf + 4);
1858 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1860 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1861 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1866 attrs = rq->buf + 20;
1868 if (!attrvalidate(attrs, len)) {
1869 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1873 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1874 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
1875 debug(DBG_WARN, "radsrv: message authentication failed");
1879 if (code == RAD_Status_Server) {
1880 respondstatusserver(rq);
1884 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1886 if (code == RAD_Accounting_Request) {
1887 memset(newauth, 0, 16);
1888 if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
1889 debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
1894 if (rq->from->conf->rewritein) {
1895 if (!dorewrite(&rq->buf, rq->from->conf->rewritein))
1897 len = RADLEN(rq->buf) - 20;
1898 auth = (uint8_t *)(rq->buf + 4);
1899 attrs = rq->buf + 20;
1902 attr = attrget(attrs, len, RAD_Attr_User_Name);
1904 if (code == RAD_Accounting_Request) {
1905 acclog(attrs, len, rq->from->conf->host);
1906 respondaccounting(rq);
1908 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1911 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1912 username[ATTRVALLEN(attr)] = '\0';
1913 radattr2ascii(userascii, sizeof(userascii), attr);
1915 if (rq->from->conf->rewriteusername) {
1916 if (!rewriteusername(rq, attr, username)) {
1917 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1920 len = RADLEN(rq->buf) - 20;
1921 auth = (uint8_t *)(rq->buf + 4);
1922 attrs = rq->buf + 20;
1925 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
1927 to = findserver(&realm, username, code == RAD_Accounting_Request);
1929 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1933 if (realm->message && code == RAD_Access_Request) {
1934 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
1935 respondreject(rq, realm->message);
1936 } else if (realm->accresp && code == RAD_Accounting_Request) {
1937 acclog(attrs, len, rq->from->conf->host);
1938 respondaccounting(rq);
1943 if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
1944 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
1945 rq->from->conf->name, to->conf->name);
1949 if (rqinqueue(to, rq->from, id, code)) {
1950 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
1951 radmsgtype2string(code), rq->from->conf->host, id);
1955 if (code != RAD_Accounting_Request) {
1956 if (!RAND_bytes(newauth, 16)) {
1957 debug(DBG_WARN, "radsrv: failed to generate random auth");
1963 printfchars(NULL, "auth", "%02x ", auth, 16);
1966 attr = attrget(attrs, len, RAD_Attr_User_Password);
1968 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1969 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
1973 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1975 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1976 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
1981 memcpy(rq->origauth, auth, 16);
1982 memcpy(auth, newauth, 16);
1984 if (to->conf->rewriteout)
1985 if (!dorewrite(&rq->buf, to->conf->rewriteout))
2000 int replyh(struct server *server, unsigned char *buf) {
2001 struct client *from;
2004 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
2005 struct sockaddr_storage fromsa;
2006 char tmp[760], stationid[760];
2008 server->connectionok = 1;
2009 server->lostrqs = 0;
2011 i = buf[1]; /* i is the id */
2013 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
2014 && *buf != RAD_Accounting_Response) {
2015 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
2018 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
2020 rq = server->requests + i;
2022 pthread_mutex_lock(&server->newrq_mutex);
2023 if (!rq->buf || !rq->tries) {
2024 pthread_mutex_unlock(&server->newrq_mutex);
2025 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
2030 pthread_mutex_unlock(&server->newrq_mutex);
2031 debug(DBG_INFO, "replyh: already received, ignoring reply");
2035 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
2036 pthread_mutex_unlock(&server->newrq_mutex);
2037 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
2041 len = RADLEN(buf) - 20;
2044 if (!attrvalidate(attrs, len)) {
2045 pthread_mutex_unlock(&server->newrq_mutex);
2046 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
2050 /* Message Authenticator */
2051 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2053 if (ATTRVALLEN(messageauth) != 16) {
2054 pthread_mutex_unlock(&server->newrq_mutex);
2055 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
2058 memcpy(tmp, buf + 4, 16);
2059 memcpy(buf + 4, rq->buf + 4, 16);
2060 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
2061 pthread_mutex_unlock(&server->newrq_mutex);
2062 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
2065 memcpy(buf + 4, tmp, 16);
2066 debug(DBG_DBG, "replyh: message auth ok");
2069 gettimeofday(&server->lastrcv, NULL);
2071 if (*rq->buf == RAD_Status_Server) {
2073 pthread_mutex_unlock(&server->newrq_mutex);
2074 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2078 gettimeofday(&server->lastreply, NULL);
2082 pthread_mutex_unlock(&server->newrq_mutex);
2083 debug(DBG_INFO, "replyh: client gone, ignoring reply");
2087 if (server->conf->rewritein) {
2088 if (!dorewrite(&buf, server->conf->rewritein))
2090 len = RADLEN(buf) - 20;
2093 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2097 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2098 if (ATTRVALLEN(attr) <= 4)
2101 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
2104 sublen = ATTRVALLEN(attr) - 4;
2105 subattrs = ATTRVAL(attr) + 4;
2106 if (!attrvalidate(subattrs, sublen) ||
2107 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2108 rq, server->conf->secret, from->conf->secret) ||
2109 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2110 rq, server->conf->secret, from->conf->secret))
2114 pthread_mutex_unlock(&server->newrq_mutex);
2115 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2119 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2120 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2122 radattr2ascii(tmp, sizeof(tmp), attr);
2123 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2125 radattr2ascii(stationid, sizeof(stationid), attr);
2126 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2127 radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2129 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2133 buf[1] = (char)rq->origid;
2134 memcpy(buf + 4, rq->origauth, 16);
2136 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2139 if (rq->origusername && (attr = attrget(buf + 20, RADLEN(buf) - 20, RAD_Attr_User_Name))) {
2140 username = resizeattr(&buf, &attr, strlen(rq->origusername));
2142 pthread_mutex_unlock(&server->newrq_mutex);
2143 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2146 memcpy(username, rq->origusername, strlen(rq->origusername));
2147 len = RADLEN(buf) - 20;
2150 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2153 if (from->conf->rewriteout) {
2154 if (!dorewrite(&buf, from->conf->rewriteout))
2156 len = RADLEN(buf) - 20;
2159 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2163 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2164 pthread_mutex_unlock(&server->newrq_mutex);
2165 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2168 debug(DBG_DBG, "replyh: computed messageauthattr");
2171 fromsa = rq->fromsa; /* only needed for UDP */
2172 /* once we set received = 1, rq may be reused */
2175 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2176 sendreply(from, buf, &fromsa, rq->fromudpsock);
2177 pthread_mutex_unlock(&server->newrq_mutex);
2181 /* code for removing state not finished */
2182 void *clientwr(void *arg) {
2183 struct server *server = (struct server *)arg;
2185 pthread_t clientrdth;
2186 int i, secs, dynconffail = 0;
2188 struct timeval now, laststatsrv;
2189 struct timespec timeout;
2190 struct request statsrvrq;
2191 unsigned char statsrvbuf[38];
2192 struct clsrvconf *conf;
2194 conf = server->conf;
2196 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2201 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2202 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2206 memset(&timeout, 0, sizeof(struct timespec));
2208 if (conf->statusserver) {
2209 memset(&statsrvrq, 0, sizeof(struct request));
2210 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2211 statsrvbuf[0] = RAD_Status_Server;
2213 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2214 statsrvbuf[21] = 18;
2215 gettimeofday(&server->lastrcv, NULL);
2216 gettimeofday(&laststatsrv, NULL);
2219 if (conf->pdef->connecter) {
2220 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2222 server->connectionok = 1;
2223 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
2224 debug(DBG_ERR, "clientwr: pthread_create failed");
2228 server->connectionok = 1;
2231 pthread_mutex_lock(&server->newrq_mutex);
2232 if (!server->newrq) {
2233 gettimeofday(&now, NULL);
2234 /* random 0-7 seconds */
2235 RAND_bytes(&rnd, 1);
2237 if (conf->statusserver) {
2238 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2239 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
2240 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
2242 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2243 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2246 if (timeout.tv_sec > now.tv_sec)
2247 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2249 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2252 if (server->newrq) {
2253 debug(DBG_DBG, "clientwr: got new request");
2258 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2260 pthread_mutex_unlock(&server->newrq_mutex);
2262 for (i = 0; i < MAX_REQUESTS; i++) {
2263 if (server->clientrdgone) {
2264 pthread_join(clientrdth, NULL);
2267 pthread_mutex_lock(&server->newrq_mutex);
2268 while (i < MAX_REQUESTS && !server->requests[i].buf)
2270 if (i == MAX_REQUESTS) {
2271 pthread_mutex_unlock(&server->newrq_mutex);
2274 rq = server->requests + i;
2277 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2279 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2281 /* setting this to NULL means that it can be reused */
2284 pthread_mutex_unlock(&server->newrq_mutex);
2288 gettimeofday(&now, NULL);
2289 if (now.tv_sec < rq->expiry.tv_sec) {
2290 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2291 timeout.tv_sec = rq->expiry.tv_sec;
2292 pthread_mutex_unlock(&server->newrq_mutex);
2296 if (rq->tries == (*rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2297 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2298 if (conf->statusserver) {
2299 if (*rq->buf == RAD_Status_Server) {
2300 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2301 if (server->lostrqs < 255)
2305 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2306 if (server->lostrqs < 255)
2310 /* setting this to NULL means that it can be reused */
2312 pthread_mutex_unlock(&server->newrq_mutex);
2315 pthread_mutex_unlock(&server->newrq_mutex);
2317 rq->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2318 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2319 timeout.tv_sec = rq->expiry.tv_sec;
2321 conf->pdef->clientradput(server, server->requests[i].buf);
2323 if (conf->statusserver) {
2324 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2325 gettimeofday(&now, NULL);
2326 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
2328 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2329 debug(DBG_WARN, "clientwr: failed to generate random auth");
2332 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2333 if (!statsrvrq.buf) {
2334 debug(DBG_ERR, "clientwr: malloc failed");
2337 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2338 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2339 sendrq(server, &statsrvrq);
2344 conf->servers = NULL;
2345 if (server->dynamiclookuparg) {
2346 removeserversubrealms(realms, conf);
2350 freeclsrvconf(conf);
2352 freeserver(server, 1);
2353 ERR_remove_state(0);
2357 void createlistener(uint8_t type, char *arg) {
2359 struct clsrvconf *listenres;
2360 struct addrinfo *res;
2361 int s = -1, on = 1, *sp = NULL;
2363 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2365 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2367 for (res = listenres->addrinfo; res; res = res->ai_next) {
2368 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2370 debug(DBG_WARN, "createlistener: socket failed");
2373 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2375 if (res->ai_family == AF_INET6)
2376 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2378 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2379 debug(DBG_WARN, "createlistener: bind failed");
2385 sp = malloc(sizeof(int));
2387 debugx(1, DBG_ERR, "malloc failed");
2389 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
2390 debugx(1, DBG_ERR, "pthread_create failed");
2394 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2396 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
2397 listenres->host ? listenres->host : "*", listenres->port);
2398 freeclsrvres(listenres);
2401 void createlisteners(uint8_t type, char **args) {
2405 for (i = 0; args[i]; i++)
2406 createlistener(type, args[i]);
2408 createlistener(type, NULL);
2412 void ssl_info_callback(const SSL *ssl, int where, int ret) {
2416 w = where & ~SSL_ST_MASK;
2418 if (w & SSL_ST_CONNECT)
2420 else if (w & SSL_ST_ACCEPT)
2425 if (where & SSL_CB_LOOP)
2426 debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
2427 else if (where & SSL_CB_ALERT) {
2428 s = (where & SSL_CB_READ) ? "read" : "write";
2429 debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
2431 else if (where & SSL_CB_EXIT) {
2433 debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
2435 debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
2440 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2441 SSL_CTX *ctx = NULL;
2442 STACK_OF(X509_NAME) *calist;
2445 unsigned long error;
2448 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2449 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2450 for (i = 0; i < CRYPTO_num_locks(); i++) {
2451 ssl_lock_count[i] = 0;
2452 pthread_mutex_init(&ssl_locks[i], NULL);
2454 CRYPTO_set_id_callback(ssl_thread_id);
2455 CRYPTO_set_locking_callback(ssl_locking_callback);
2457 SSL_load_error_strings();
2460 while (!RAND_status()) {
2461 time_t t = time(NULL);
2462 pid_t pid = getpid();
2463 RAND_seed((unsigned char *)&t, sizeof(time_t));
2464 RAND_seed((unsigned char *)&pid, sizeof(pid));
2470 ctx = SSL_CTX_new(TLSv1_method());
2472 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2476 ctx = SSL_CTX_new(DTLSv1_method());
2478 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2480 SSL_CTX_set_read_ahead(ctx, 1);
2484 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2488 if (conf->certkeypwd) {
2489 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2490 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2492 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2493 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2494 !SSL_CTX_check_private_key(ctx) ||
2495 !SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2496 while ((error = ERR_get_error()))
2497 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2498 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2503 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2504 if (!conf->cacertfile || calist) {
2505 if (conf->cacertpath) {
2507 calist = sk_X509_NAME_new_null();
2508 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2509 sk_X509_NAME_free(calist);
2515 while ((error = ERR_get_error()))
2516 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2517 debug(DBG_ERR, "tlscreatectx: Error adding CA subjects in TLS context %s", conf->name);
2521 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2522 SSL_CTX_set_client_CA_list(ctx, calist);
2524 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2525 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2527 if (conf->crlcheck) {
2528 x509_s = SSL_CTX_get_cert_store(ctx);
2529 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2532 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
2536 SSL_CTX *tlsgetctx(uint8_t type, char *alt1, char *alt2) {
2539 t = hash_read(tlsconfs, alt1, strlen(alt1));
2541 t = hash_read(tlsconfs, alt2, strlen(alt2));
2549 t->tlsctx = tlscreatectx(RAD_TLS, t);
2553 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2559 struct list *addsrvconfs(char *value, char **names) {
2560 struct list *conflist;
2562 struct list_node *entry;
2563 struct clsrvconf *conf = NULL;
2565 if (!names || !*names)
2568 conflist = list_create();
2570 debug(DBG_ERR, "malloc failed");
2574 for (n = 0; names[n]; n++) {
2575 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2576 conf = (struct clsrvconf *)entry->data;
2577 if (!strcasecmp(names[n], conf->name))
2581 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2582 list_destroy(conflist);
2585 if (!list_push(conflist, conf)) {
2586 debug(DBG_ERR, "malloc failed");
2587 list_destroy(conflist);
2590 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2595 void freerealm(struct realm *realm) {
2599 free(realm->message);
2600 regfree(&realm->regex);
2601 pthread_mutex_destroy(&realm->subrealms_mutex);
2602 if (realm->subrealms)
2603 list_destroy(realm->subrealms);
2604 if (realm->srvconfs) {
2605 /* emptying list without freeing data */
2606 while (list_shift(realm->srvconfs));
2607 list_destroy(realm->srvconfs);
2609 if (realm->accsrvconfs) {
2610 /* emptying list without freeing data */
2611 while (list_shift(realm->accsrvconfs));
2612 list_destroy(realm->accsrvconfs);
2617 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2619 struct realm *realm;
2620 char *s, *regex = NULL;
2622 if (*value == '/') {
2623 /* regexp, remove optional trailing / if present */
2624 if (value[strlen(value) - 1] == '/')
2625 value[strlen(value) - 1] = '\0';
2627 /* not a regexp, let us make it one */
2628 if (*value == '*' && !value[1])
2629 regex = stringcopy(".*", 0);
2631 for (n = 0, s = value; *s;)
2634 regex = malloc(strlen(value) + n + 3);
2637 for (n = 1, s = value; *s; s++) {
2647 debug(DBG_ERR, "malloc failed");
2651 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2654 realm = malloc(sizeof(struct realm));
2656 debug(DBG_ERR, "malloc failed");
2659 memset(realm, 0, sizeof(struct realm));
2661 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
2662 debug(DBG_ERR, "mutex init failed");
2668 realm->name = stringcopy(value, 0);
2670 debug(DBG_ERR, "malloc failed");
2673 if (message && strlen(message) > 253) {
2674 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2677 realm->message = message;
2678 realm->accresp = accresp;
2680 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2681 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2685 if (servers && *servers) {
2686 realm->srvconfs = addsrvconfs(value, servers);
2687 if (!realm->srvconfs)
2691 if (accservers && *accservers) {
2692 realm->accsrvconfs = addsrvconfs(value, accservers);
2693 if (!realm->accsrvconfs)
2697 if (!list_push(realmlist, realm)) {
2698 debug(DBG_ERR, "malloc failed");
2699 pthread_mutex_destroy(&realm->subrealms_mutex);
2703 debug(DBG_DBG, "addrealm: added realm %s", value);
2713 for (n = 0; servers[n]; n++)
2718 for (n = 0; accservers[n]; n++)
2719 free(accservers[n]);
2725 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2726 struct clsrvconf *srvconf;
2727 struct realm *newrealm = NULL;
2728 char *realmname, *s;
2731 if (!conf->dynamiclookupcommand)
2734 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2735 realmname = strrchr(id, '@');
2741 for (s = realmname; *s; s++)
2742 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2745 pthread_mutex_lock(&realm->subrealms_mutex);
2746 /* exit if we now already got a matching subrealm */
2747 if (id2realm(realm->subrealms, id))
2749 srvconf = malloc(sizeof(struct clsrvconf));
2751 debug(DBG_ERR, "malloc failed");
2755 if (!addserver(srvconf))
2758 if (!realm->subrealms)
2759 realm->subrealms = list_create();
2760 if (!realm->subrealms)
2762 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2766 /* add server and accserver to newrealm */
2767 newrealm->srvconfs = list_create();
2768 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2769 debug(DBG_ERR, "malloc failed");
2772 newrealm->accsrvconfs = list_create();
2773 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2774 debug(DBG_ERR, "malloc failed");
2778 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2780 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2781 debug(DBG_ERR, "pthread_create failed");
2784 pthread_detach(clientth);
2789 list_removedata(realm->subrealms, newrealm);
2790 freerealm(newrealm);
2791 if (!list_first(realm->subrealms)) {
2792 list_destroy(realm->subrealms);
2793 realm->subrealms = NULL;
2796 freeserver(srvconf->servers, 1);
2798 debug(DBG_ERR, "failed to create dynamic server");
2801 pthread_mutex_unlock(&realm->subrealms_mutex);
2804 int dynamicconfig(struct server *server) {
2805 int ok, fd[2], status;
2807 struct clsrvconf *conf = server->conf;
2808 struct gconffile *cf = NULL;
2810 /* for now we only learn hostname/address */
2811 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2814 debug(DBG_ERR, "dynamicconfig: pipe error");
2819 debug(DBG_ERR, "dynamicconfig: fork error");
2823 } else if (pid == 0) {
2826 if (fd[1] != STDOUT_FILENO) {
2827 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2828 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2831 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2832 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2836 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2837 ok = getgenericconfig(&cf, NULL,
2838 "Server", CONF_CBK, confserver_cb, (void *)conf,
2843 if (waitpid(pid, &status, 0) < 0) {
2844 debug(DBG_ERR, "dynamicconfig: wait error");
2849 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2857 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2861 int addmatchcertattr(struct clsrvconf *conf) {
2865 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2866 r = &conf->certcnregex;
2867 v = conf->matchcertattr + 4;
2868 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2869 r = &conf->certuriregex;
2870 v = conf->matchcertattr + 20;
2875 /* regexp, remove optional trailing / if present */
2876 if (v[strlen(v) - 1] == '/')
2877 v[strlen(v) - 1] = '\0';
2881 *r = malloc(sizeof(regex_t));
2883 debug(DBG_ERR, "malloc failed");
2886 if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2889 debug(DBG_ERR, "failed to compile regular expression %s", v);
2895 /* should accept both names and numeric values, only numeric right now */
2896 uint8_t attrname2val(char *attrname) {
2899 val = atoi(attrname);
2900 return val > 0 && val < 256 ? val : 0;
2903 /* should accept both names and numeric values, only numeric right now */
2904 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2907 *vendor = atoi(attrname);
2908 s = strchr(attrname, ':');
2913 *type = atoi(s + 1);
2914 return *type >= 0 && *type < 256;
2917 /* should accept both names and numeric values, only numeric right now */
2918 struct attribute *extractattr(char *nameval) {
2921 struct attribute *a;
2923 s = strchr(nameval, ':');
2924 name = atoi(nameval);
2925 if (!s || name < 1 || name > 255)
2927 len = strlen(s + 1);
2930 a = malloc(sizeof(struct attribute));
2933 a->v = (uint8_t *)stringcopy(s + 1, 0);
2943 /* should accept both names and numeric values, only numeric right now */
2944 struct modattr *extractmodattr(char *nameval) {
2949 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2953 s = strchr(nameval, ':');
2954 name = atoi(nameval);
2955 if (!s || name < 1 || name > 255 || s[1] != '/')
2959 /* regexp, remove optional trailing / if present */
2960 if (s[strlen(s) - 1] == '/')
2961 s[strlen(s) - 1] = '\0';
2969 m = malloc(sizeof(struct modattr));
2971 debug(DBG_ERR, "malloc failed");
2976 m->replacement = stringcopy(t, 0);
2977 if (!m->replacement) {
2979 debug(DBG_ERR, "malloc failed");
2983 m->regex = malloc(sizeof(regex_t));
2985 free(m->replacement);
2987 debug(DBG_ERR, "malloc failed");
2991 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2993 free(m->replacement);
2995 debug(DBG_ERR, "failed to compile regular expression %s", s);
3002 struct rewrite *getrewrite(char *alt1, char *alt2) {
3005 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
3007 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
3012 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
3013 struct rewrite *rewrite = NULL;
3015 uint8_t *rma = NULL;
3016 uint32_t *p, *rmva = NULL;
3017 struct list *adda = NULL, *moda = NULL;
3018 struct attribute *a;
3022 for (n = 0; rmattrs[n]; n++);
3023 rma = calloc(n + 1, sizeof(uint8_t));
3025 debugx(1, DBG_ERR, "malloc failed");
3027 for (i = 0; i < n; i++) {
3028 if (!(rma[i] = attrname2val(rmattrs[i])))
3029 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
3037 for (n = 0; rmvattrs[n]; n++);
3038 rmva = calloc(2 * n + 1, sizeof(uint32_t));
3040 debugx(1, DBG_ERR, "malloc failed");
3042 for (p = rmva, i = 0; i < n; i++, p += 2) {
3043 if (!vattrname2val(rmvattrs[i], p, p + 1))
3044 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
3052 adda = list_create();
3054 debugx(1, DBG_ERR, "malloc failed");
3055 for (i = 0; addattrs[i]; i++) {
3056 a = extractattr(addattrs[i]);
3058 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
3060 if (!list_push(adda, a))
3061 debugx(1, DBG_ERR, "malloc failed");
3067 moda = list_create();
3069 debugx(1, DBG_ERR, "malloc failed");
3070 for (i = 0; modattrs[i]; i++) {
3071 m = extractmodattr(modattrs[i]);
3073 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
3075 if (!list_push(moda, m))
3076 debugx(1, DBG_ERR, "malloc failed");
3081 if (rma || rmva || adda || moda) {
3082 rewrite = malloc(sizeof(struct rewrite));
3084 debugx(1, DBG_ERR, "malloc failed");
3085 rewrite->removeattrs = rma;
3086 rewrite->removevendorattrs = rmva;
3087 rewrite->addattrs = adda;
3088 rewrite->modattrs = moda;
3091 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
3092 debugx(1, DBG_ERR, "malloc failed");
3093 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3096 void freeclsrvconf(struct clsrvconf *conf) {
3102 free(conf->matchcertattr);
3103 if (conf->certcnregex)
3104 regfree(conf->certcnregex);
3105 if (conf->certuriregex)
3106 regfree(conf->certuriregex);
3107 free(conf->confrewritein);
3108 free(conf->confrewriteout);
3109 if (conf->rewriteusername) {
3110 if (conf->rewriteusername->regex)
3111 regfree(conf->rewriteusername->regex);
3112 free(conf->rewriteusername->replacement);
3113 free(conf->rewriteusername);
3115 free(conf->dynamiclookupcommand);
3116 free(conf->rewritein);
3117 free(conf->rewriteout);
3119 freeaddrinfo(conf->addrinfo);
3120 /* not touching ssl_ctx, clients and servers */
3124 int mergeconfstring(char **dst, char **src) {
3133 t = stringcopy(*dst, 0);
3135 debug(DBG_ERR, "malloc failed");
3143 /* assumes dst is a shallow copy */
3144 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3145 if (!mergeconfstring(&dst->name, &src->name) ||
3146 !mergeconfstring(&dst->host, &src->host) ||
3147 !mergeconfstring(&dst->port, &src->port) ||
3148 !mergeconfstring(&dst->secret, &src->secret) ||
3149 !mergeconfstring(&dst->tls, &src->tls) ||
3150 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3151 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
3152 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
3153 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3156 dst->pdef = src->pdef;
3157 dst->statusserver = src->statusserver;
3158 dst->certnamecheck = src->certnamecheck;
3159 if (src->retryinterval != 255)
3160 dst->retryinterval = src->retryinterval;
3161 if (src->retrycount != 255)
3162 dst->retrycount = src->retrycount;
3166 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3167 struct clsrvconf *conf;
3168 char *conftype = NULL, *rewriteinalias = NULL;
3170 debug(DBG_DBG, "confclient_cb called for %s", block);
3172 conf = malloc(sizeof(struct clsrvconf));
3173 if (!conf || !list_push(clconfs, conf))
3174 debugx(1, DBG_ERR, "malloc failed");
3175 memset(conf, 0, sizeof(struct clsrvconf));
3176 conf->certnamecheck = 1;
3178 if (!getgenericconfig(cf, block,
3179 "type", CONF_STR, &conftype,
3180 "host", CONF_STR, &conf->host,
3181 "secret", CONF_STR, &conf->secret,
3182 "tls", CONF_STR, &conf->tls,
3183 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3184 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3185 "rewrite", CONF_STR, &rewriteinalias,
3186 "rewriteIn", CONF_STR, &conf->confrewritein,
3187 "rewriteOut", CONF_STR, &conf->confrewriteout,
3188 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
3191 debugx(1, DBG_ERR, "configuration error");
3193 conf->name = stringcopy(val, 0);
3195 conf->host = stringcopy(val, 0);
3196 if (!conf->name || !conf->host)
3197 debugx(1, DBG_ERR, "malloc failed");
3200 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3201 conf->type = protoname2int(conftype);
3202 conf->pdef = &protodefs[conf->type];
3203 if (!conf->pdef->name)
3204 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3207 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3208 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultclient", "default");
3210 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3211 if (conf->matchcertattr && !addmatchcertattr(conf))
3212 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3215 if (!conf->confrewritein)
3216 conf->confrewritein = rewriteinalias;
3218 free(rewriteinalias);
3219 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
3220 if (conf->confrewriteout)
3221 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3223 if (conf->confrewriteusername) {
3224 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
3225 if (!conf->rewriteusername)
3226 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3229 if (!resolvepeer(conf, 0))
3230 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3232 if (!conf->secret) {
3233 if (!conf->pdef->secretdefault)
3234 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3235 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3237 debugx(1, DBG_ERR, "malloc failed");
3242 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3243 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3244 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultserver", "default");
3245 if (!conf->ssl_ctx) {
3246 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3249 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3250 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3256 conf->port = stringcopy(conf->pdef->portdefault, 0);
3258 debug(DBG_ERR, "malloc failed");
3263 if (conf->retryinterval == 255)
3264 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3265 if (conf->retrycount == 255)
3266 conf->retrycount = protodefs[conf->type].retrycountdefault;
3268 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
3269 if (conf->confrewriteout)
3270 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3272 if (!conf->secret) {
3273 if (!conf->pdef->secretdefault) {
3274 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3277 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3278 if (!conf->secret) {
3279 debug(DBG_ERR, "malloc failed");
3284 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3285 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3291 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3292 struct clsrvconf *conf, *resconf;
3293 char *conftype = NULL, *rewriteinalias = NULL;
3294 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3296 debug(DBG_DBG, "confserver_cb called for %s", block);
3298 conf = malloc(sizeof(struct clsrvconf));
3300 debug(DBG_ERR, "malloc failed");
3303 memset(conf, 0, sizeof(struct clsrvconf));
3304 resconf = (struct clsrvconf *)arg;
3306 conf->statusserver = resconf->statusserver;
3307 conf->certnamecheck = resconf->certnamecheck;
3309 conf->certnamecheck = 1;
3311 if (!getgenericconfig(cf, block,
3312 "type", CONF_STR, &conftype,
3313 "host", CONF_STR, &conf->host,
3314 "port", CONF_STR, &conf->port,
3315 "secret", CONF_STR, &conf->secret,
3316 "tls", CONF_STR, &conf->tls,
3317 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3318 "rewrite", CONF_STR, &rewriteinalias,
3319 "rewriteIn", CONF_STR, &conf->confrewritein,
3320 "rewriteOut", CONF_STR, &conf->confrewriteout,
3321 "StatusServer", CONF_BLN, &conf->statusserver,
3322 "RetryInterval", CONF_LINT, &retryinterval,
3323 "RetryCount", CONF_LINT, &retrycount,
3324 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3325 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3328 debug(DBG_ERR, "configuration error");
3332 conf->name = stringcopy(val, 0);
3334 debug(DBG_ERR, "malloc failed");
3338 conf->host = stringcopy(val, 0);
3340 debug(DBG_ERR, "malloc failed");
3346 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3347 conf->type = protoname2int(conftype);
3348 conf->pdef = &protodefs[conf->type];
3349 if (!conf->pdef->name) {
3350 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3356 if (!conf->confrewritein)
3357 conf->confrewritein = rewriteinalias;
3359 free(rewriteinalias);
3360 rewriteinalias = NULL;
3362 if (retryinterval != LONG_MIN) {
3363 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3364 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3367 conf->retryinterval = (uint8_t)retryinterval;
3369 conf->retryinterval = 255;
3371 if (retrycount != LONG_MIN) {
3372 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3373 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3376 conf->retrycount = (uint8_t)retrycount;
3378 conf->retrycount = 255;
3381 if (!mergesrvconf(resconf, conf))
3385 if (conf->dynamiclookupcommand) {
3386 free(conf->dynamiclookupcommand);
3387 conf->dynamiclookupcommand = NULL;
3391 if (resconf || !conf->dynamiclookupcommand) {
3392 if (!compileserverconfig(conf, block))
3399 if (!list_push(srvconfs, conf)) {
3400 debug(DBG_ERR, "malloc failed");
3407 free(rewriteinalias);
3408 freeclsrvconf(conf);
3412 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3413 char **servers = NULL, **accservers = NULL, *msg = NULL;
3414 uint8_t accresp = 0;
3416 debug(DBG_DBG, "confrealm_cb called for %s", block);
3418 if (!getgenericconfig(cf, block,
3419 "server", CONF_MSTR, &servers,
3420 "accountingServer", CONF_MSTR, &accservers,
3421 "ReplyMessage", CONF_STR, &msg,
3422 "AccountingResponse", CONF_BLN, &accresp,
3425 debugx(1, DBG_ERR, "configuration error");
3427 addrealm(realms, val, servers, accservers, msg, accresp);
3431 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3434 debug(DBG_DBG, "conftls_cb called for %s", block);
3436 conf = malloc(sizeof(struct tls));
3438 debug(DBG_ERR, "conftls_cb: malloc failed");
3441 memset(conf, 0, sizeof(struct tls));
3443 if (!getgenericconfig(cf, block,
3444 "CACertificateFile", CONF_STR, &conf->cacertfile,
3445 "CACertificatePath", CONF_STR, &conf->cacertpath,
3446 "CertificateFile", CONF_STR, &conf->certfile,
3447 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3448 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3449 "CRLCheck", CONF_BLN, &conf->crlcheck,
3452 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3455 if (!conf->certfile || !conf->certkeyfile) {
3456 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3459 if (!conf->cacertfile && !conf->cacertpath) {
3460 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3464 conf->name = stringcopy(val, 0);
3466 debug(DBG_ERR, "conftls_cb: malloc failed");
3470 if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
3471 debug(DBG_ERR, "conftls_cb: malloc failed");
3475 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3479 free(conf->cacertfile);
3480 free(conf->cacertpath);
3481 free(conf->certfile);
3482 free(conf->certkeyfile);
3483 free(conf->certkeypwd);
3488 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3489 char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3491 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3493 if (!getgenericconfig(cf, block,
3494 "removeAttribute", CONF_MSTR, &rmattrs,
3495 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3496 "addAttribute", CONF_MSTR, &addattrs,
3497 "modifyAttribute", CONF_MSTR, &modattrs,
3500 debugx(1, DBG_ERR, "configuration error");
3501 addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3505 void getmainconfig(const char *configfile) {
3506 long int loglevel = LONG_MIN;
3507 struct gconffile *cfs;
3509 cfs = openconfigfile(configfile);
3510 memset(&options, 0, sizeof(options));
3512 clconfs = list_create();
3514 debugx(1, DBG_ERR, "malloc failed");
3516 srvconfs = list_create();
3518 debugx(1, DBG_ERR, "malloc failed");
3520 realms = list_create();
3522 debugx(1, DBG_ERR, "malloc failed");
3524 tlsconfs = hash_create();
3526 debugx(1, DBG_ERR, "malloc failed");
3528 rewriteconfs = hash_create();
3530 debugx(1, DBG_ERR, "malloc failed");
3532 if (!getgenericconfig(&cfs, NULL,
3533 "ListenUDP", CONF_MSTR, &options.listenudp,
3534 "ListenTCP", CONF_MSTR, &options.listentcp,
3535 "ListenTLS", CONF_MSTR, &options.listentls,
3536 "ListenDTLS", CONF_MSTR, &options.listendtls,
3537 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
3538 "SourceUDP", CONF_STR, &options.sourceudp,
3539 "SourceTCP", CONF_STR, &options.sourcetcp,
3540 "SourceTLS", CONF_STR, &options.sourcetls,
3541 "SourceDTLS", CONF_STR, &options.sourcedtls,
3542 "LogLevel", CONF_LINT, &loglevel,
3543 "LogDestination", CONF_STR, &options.logdestination,
3544 "LoopPrevention", CONF_BLN, &options.loopprevention,
3545 "Client", CONF_CBK, confclient_cb, NULL,
3546 "Server", CONF_CBK, confserver_cb, NULL,
3547 "Realm", CONF_CBK, confrealm_cb, NULL,
3548 "TLS", CONF_CBK, conftls_cb, NULL,
3549 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3552 debugx(1, DBG_ERR, "configuration error");
3554 if (loglevel != LONG_MIN) {
3555 if (loglevel < 1 || loglevel > 4)
3556 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3557 options.loglevel = (uint8_t)loglevel;
3561 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3564 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3567 *configfile = optarg;
3570 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3571 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3572 *loglevel = *optarg - '0';
3581 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3586 if (!(argc - optind))
3590 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3594 int daemon(int a, int b) {
3602 for (i = 0; i < 3; i++) {
3604 open("/dev/null", O_RDWR);
3610 void *sighandler(void *arg) {
3615 sigemptyset(&sigset);
3616 sigaddset(&sigset, SIGPIPE);
3617 sigwait(&sigset, &sig);
3618 /* only get SIGPIPE right now, so could simplify below code */
3621 /* completely ignoring this */
3624 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3627 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3632 int main(int argc, char **argv) {
3635 struct list_node *entry;
3636 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3637 char *configfile = NULL;
3638 struct clsrvconf *srvconf;
3641 debug_init("radsecproxy");
3642 debug_set_level(DEBUG_LEVEL);
3644 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3646 debug_set_level(loglevel);
3647 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3649 options.loglevel = loglevel;
3650 else if (options.loglevel)
3651 debug_set_level(options.loglevel);
3653 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3654 free(options.logdestination);
3656 if (!list_first(clconfs))
3657 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3658 if (!list_first(realms))
3659 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3662 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3664 if (!foreground && (daemon(0, 0) < 0))
3665 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3667 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3669 sigemptyset(&sigset);
3670 /* exit on all but SIGPIPE, ignore more? */
3671 sigaddset(&sigset, SIGPIPE);
3672 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3673 pthread_create(&sigth, NULL, sighandler, NULL);
3675 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3676 srvconf = (struct clsrvconf *)entry->data;
3677 if (srvconf->dynamiclookupcommand)
3679 if (!addserver(srvconf))
3680 debugx(1, DBG_ERR, "failed to add server");
3681 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3682 (void *)(srvconf->servers)))
3683 debugx(1, DBG_ERR, "pthread_create failed");
3685 /* srcprotores for UDP no longer needed */
3686 if (srcprotores[RAD_UDP]) {
3687 freeaddrinfo(srcprotores[RAD_UDP]);
3688 srcprotores[RAD_UDP] = NULL;
3691 for (i = 0; protodefs[i].name; i++)
3692 if (protodefs[i].initextra)
3693 protodefs[i].initextra();
3695 if (find_clconf_type(RAD_TCP, NULL))
3696 createlisteners(RAD_TCP, options.listentcp);
3698 if (find_clconf_type(RAD_TLS, NULL))
3699 createlisteners(RAD_TLS, options.listentls);
3701 if (find_clconf_type(RAD_DTLS, NULL))
3702 createlisteners(RAD_DTLS, options.listendtls);
3704 if (find_clconf_type(RAD_UDP, NULL)) {
3705 createlisteners(RAD_UDP, options.listenudp);
3706 if (options.listenaccudp)
3707 createlisteners(RAD_UDP, options.listenaccudp);
3710 /* just hang around doing nothing, anything to do here? */