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 /* Code contributions from:
11 * Arne Schwabe <schwabe at uni-paderborn.de>
14 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
15 * rd is responsible for init and launching wr
16 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
17 * each tlsserverrd launches tlsserverwr
18 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
19 * for init and launching rd
21 * serverrd will receive a request, processes it and puts it in the requestq of
22 * the appropriate clientwr
23 * clientwr monitors its requestq and sends requests
24 * clientrd looks for responses, processes them and puts them in the replyq of
25 * the peer the request came from
26 * serverwr monitors its reply and sends replies
28 * In addition to the main thread, we have:
29 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
30 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
31 * For each TLS peer connecting to us there will be 2 more TLS threads
32 * This is only for connected peers
33 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
34 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
38 * May segfault when dtls connections go down? More testing needed
39 * Need to remove UDP clients when no activity for a while...
40 * Remove expired stuff from clients request list?
41 * Need refcounting for configs? Bad if remove dynsrvconf while in radsrv()
42 * Multiple outgoing connections if not enough IDs? (multiple servers per conf?)
43 * Useful for TCP accounting? Now we require separate server config for alt port
47 #include <sys/socket.h>
48 #include <netinet/in.h>
57 #include <sys/types.h>
58 #include <sys/select.h>
61 #include <arpa/inet.h>
65 #include <openssl/ssl.h>
66 #include <openssl/rand.h>
67 #include <openssl/err.h>
68 #include <openssl/md5.h>
69 #include <openssl/hmac.h>
70 #include <openssl/x509v3.h>
76 #include "radsecproxy.h"
82 static struct options options;
83 static struct list *clconfs, *srvconfs;
85 struct hash *tlsconfs, *rewriteconfs;
87 static struct addrinfo *srcprotores[4] = { NULL, NULL, NULL, NULL };
89 static pthread_mutex_t *ssl_locks = NULL;
90 static long *ssl_lock_count;
94 /* minimum required declarations to avoid reordering code */
95 struct realm *adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
96 int dynamicconfig(struct server *server);
97 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
98 void freerealm(struct realm *realm);
99 void freeclsrvconf(struct clsrvconf *conf);
100 void freerq(struct request *rq);
101 void freerqoutdata(struct rqout *rqout);
102 void rmclientrq(struct request *rq, uint8_t id);
104 static const struct protodefs protodefs[] = {
105 { "udp", /* UDP, assuming RAD_UDP defined as 0 */
106 NULL, /* secretdefault */
107 SOCK_DGRAM, /* socktype */
108 "1812", /* portdefault */
109 REQUEST_RETRY_COUNT, /* retrycountdefault */
110 10, /* retrycountmax */
111 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
112 60, /* retryintervalmax */
113 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
114 udpserverrd, /* listener */
115 &options.sourceudp, /* srcaddrport */
116 NULL, /* connecter */
117 NULL, /* clientconnreader */
118 clientradputudp, /* clientradput */
119 addclientudp, /* addclient */
120 addserverextraudp, /* addserverextra */
121 initextraudp /* initextra */
123 { "tls", /* TLS, assuming RAD_TLS defined as 1 */
124 "mysecret", /* secretdefault */
125 SOCK_STREAM, /* socktype */
126 "2083", /* portdefault */
127 0, /* retrycountdefault */
128 0, /* retrycountmax */
129 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
130 60, /* retryintervalmax */
131 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
132 tlslistener, /* listener */
133 &options.sourcetls, /* srcaddrport */
134 tlsconnect, /* connecter */
135 tlsclientrd, /* clientconnreader */
136 clientradputtls, /* clientradput */
137 NULL, /* addclient */
138 NULL, /* addserverextra */
141 { "tcp", /* TCP, assuming RAD_TCP defined as 2 */
142 NULL, /* secretdefault */
143 SOCK_STREAM, /* socktype */
144 "1812", /* portdefault */
145 0, /* retrycountdefault */
146 0, /* retrycountmax */
147 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
148 60, /* retryintervalmax */
149 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
150 tcplistener, /* listener */
151 &options.sourcetcp, /* srcaddrport */
152 tcpconnect, /* connecter */
153 tcpclientrd, /* clientconnreader */
154 clientradputtcp, /* clientradput */
155 NULL, /* addclient */
156 NULL, /* addserverextra */
159 { "dtls", /* DTLS, assuming RAD_DTLS defined as 3 */
160 "mysecret", /* secretdefault */
161 SOCK_DGRAM, /* socktype */
162 "2083", /* portdefault */
163 REQUEST_RETRY_COUNT, /* retrycountdefault */
164 10, /* retrycountmax */
165 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
166 60, /* retryintervalmax */
167 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
168 udpdtlsserverrd, /* listener */
169 &options.sourcedtls, /* srcaddrport */
170 dtlsconnect, /* connecter */
171 dtlsclientrd, /* clientconnreader */
172 clientradputdtls, /* clientradput */
173 NULL, /* addclient */
174 addserverextradtls, /* addserverextra */
175 initextradtls /* initextra */
181 uint8_t protoname2int(const char *name) {
184 for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
188 /* callbacks for making OpenSSL thread safe */
189 unsigned long ssl_thread_id() {
190 return (unsigned long)pthread_self();
193 void ssl_locking_callback(int mode, int type, const char *file, int line) {
194 if (mode & CRYPTO_LOCK) {
195 pthread_mutex_lock(&ssl_locks[type]);
196 ssl_lock_count[type]++;
198 pthread_mutex_unlock(&ssl_locks[type]);
201 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
202 int pwdlen = strlen(userdata);
203 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
205 memcpy(buf, userdata, pwdlen);
209 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
214 err_cert = X509_STORE_CTX_get_current_cert(ctx);
215 err = X509_STORE_CTX_get_error(ctx);
216 depth = X509_STORE_CTX_get_error_depth(ctx);
218 if (depth > MAX_CERT_DEPTH) {
220 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
221 X509_STORE_CTX_set_error(ctx, err);
225 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
226 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
229 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
230 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
231 debug(DBG_WARN, "\tIssuer=%s", buf);
233 case X509_V_ERR_CERT_NOT_YET_VALID:
234 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
235 debug(DBG_WARN, "\tCertificate not yet valid");
237 case X509_V_ERR_CERT_HAS_EXPIRED:
238 debug(DBG_WARN, "Certificate has expired");
240 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
241 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
246 printf("certificate verify returns %d\n", ok);
251 struct addrinfo *getsrcprotores(uint8_t type) {
252 return srcprotores[type];
255 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
256 struct addrinfo hints, *addrinfo, *res;
260 slash = conf->host ? strchr(conf->host, '/') : NULL;
264 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
268 if (*s < '0' || *s > '9') {
269 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
272 plen = atoi(slash + 1);
273 if (plen < 0 || plen > 128) {
274 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
279 memset(&hints, 0, sizeof(hints));
280 hints.ai_socktype = conf->pdef->socktype;
281 hints.ai_family = AF_UNSPEC;
282 hints.ai_flags = ai_flags;
283 if (!conf->host && !conf->port) {
284 /* getaddrinfo() doesn't like host and port to be NULL */
285 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
286 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
289 for (res = addrinfo; res; res = res->ai_next)
290 port_set(res->ai_addr, 0);
293 hints.ai_flags |= AI_NUMERICHOST;
294 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
295 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
300 switch (addrinfo->ai_family) {
303 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
304 freeaddrinfo(addrinfo);
311 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
312 freeaddrinfo(addrinfo);
315 conf->prefixlen = plen;
317 conf->prefixlen = 255;
320 freeaddrinfo(conf->addrinfo);
321 conf->addrinfo = addrinfo;
325 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
330 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
334 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
336 debugx(1, DBG_ERR, "no ] matching initial [");
340 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
343 debugx(1, DBG_ERR, "missing host/address");
345 conf->host = stringcopy(field, p - field);
348 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
349 debugx(1, DBG_ERR, "unexpected character after ]");
352 /* port number or service name is specified */;
354 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
356 debugx(1, DBG_ERR, "syntax error, : but no following port");
357 conf->port = stringcopy(field, p - field);
359 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
363 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
364 struct clsrvconf *conf;
366 conf = malloc(sizeof(struct clsrvconf));
368 debugx(1, DBG_ERR, "malloc failed");
369 memset(conf, 0, sizeof(struct clsrvconf));
371 conf->pdef = &protodefs[conf->type];
373 parsehostport(lconf, conf, default_port);
374 if (!strcmp(conf->host, "*")) {
379 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
380 if (!resolvepeer(conf, AI_PASSIVE))
381 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
385 void freeclsrvres(struct clsrvconf *res) {
389 freeaddrinfo(res->addrinfo);
393 /* returns 1 if the len first bits are equal, else 0 */
394 int prefixmatch(void *a1, void *a2, uint8_t len) {
395 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
397 if (l && memcmp(a1, a2, l))
402 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
405 /* returns next config with matching address, or NULL */
406 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
407 struct sockaddr_in6 *sa6 = NULL;
408 struct in_addr *a4 = NULL;
409 struct addrinfo *res;
410 struct list_node *entry;
411 struct clsrvconf *conf;
413 if (addr->sa_family == AF_INET6) {
414 sa6 = (struct sockaddr_in6 *)addr;
415 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
416 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
420 a4 = &((struct sockaddr_in *)addr)->sin_addr;
422 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
423 conf = (struct clsrvconf *)entry->data;
424 if (conf->type == type) {
425 if (conf->prefixlen == 255) {
426 for (res = conf->addrinfo; res; res = res->ai_next)
427 if ((a4 && res->ai_family == AF_INET &&
428 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
429 (sa6 && res->ai_family == AF_INET6 &&
430 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
436 res = conf->addrinfo;
438 ((a4 && res->ai_family == AF_INET &&
439 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
440 (sa6 && res->ai_family == AF_INET6 &&
441 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
452 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
453 return find_conf(type, addr, clconfs, cur);
456 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
457 return find_conf(type, addr, srvconfs, cur);
460 /* returns next config of given type, or NULL */
461 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
462 struct list_node *entry;
463 struct clsrvconf *conf;
465 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
466 conf = (struct clsrvconf *)entry->data;
467 if (conf->type == type) {
476 struct queue *newqueue() {
479 q = malloc(sizeof(struct queue));
481 debugx(1, DBG_ERR, "malloc failed");
482 q->entries = list_create();
484 debugx(1, DBG_ERR, "malloc failed");
485 pthread_mutex_init(&q->mutex, NULL);
486 pthread_cond_init(&q->cond, NULL);
490 void removequeue(struct queue *q) {
491 struct list_node *entry;
495 pthread_mutex_lock(&q->mutex);
496 for (entry = list_first(q->entries); entry; entry = list_next(entry))
497 freerq((struct request *)entry);
498 list_destroy(q->entries);
499 pthread_cond_destroy(&q->cond);
500 pthread_mutex_unlock(&q->mutex);
501 pthread_mutex_destroy(&q->mutex);
505 void freebios(struct queue *q) {
508 pthread_mutex_lock(&q->mutex);
509 while ((bio = (BIO *)list_shift(q->entries)))
511 pthread_mutex_unlock(&q->mutex);
515 struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
516 struct client *new = malloc(sizeof(struct client));
519 debug(DBG_ERR, "malloc failed");
524 pthread_mutex_lock(conf->lock);
525 if (!conf->clients) {
526 conf->clients = list_create();
527 if (!conf->clients) {
529 pthread_mutex_unlock(conf->lock);
530 debug(DBG_ERR, "malloc failed");
535 memset(new, 0, sizeof(struct client));
537 if (conf->pdef->addclient)
538 conf->pdef->addclient(new);
540 new->replyq = newqueue();
541 list_push(conf->clients, new);
543 pthread_mutex_unlock(conf->lock);
547 void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
548 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
551 pthread_mutex_lock(&lock);
553 pthread_mutex_unlock(&lock);
556 void removeclientrqs(struct client *client) {
561 removeclientrqs_sendrq_freeserver_lock(1);
562 for (i = 0; i < MAX_REQUESTS; i++) {
567 rqout = rq->to->requests + rq->newid;
568 pthread_mutex_lock(rqout->lock);
569 if (rqout->rq == rq) /* still pointing to our request */
570 freerqoutdata(rqout);
571 pthread_mutex_unlock(rqout->lock);
575 removeclientrqs_sendrq_freeserver_lock(0);
578 void removeclient(struct client *client) {
579 struct clsrvconf *conf;
584 pthread_mutex_lock(conf->lock);
586 removeclientrqs(client);
587 removequeue(client->replyq);
588 list_removedata(conf->clients, client);
592 pthread_mutex_unlock(conf->lock);
595 void freeserver(struct server *server, uint8_t destroymutex) {
596 struct rqout *rqout, *end;
601 removeclientrqs_sendrq_freeserver_lock(1);
602 if (server->requests) {
603 rqout = server->requests;
604 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
606 rqout->rq->to = NULL;
607 freerqoutdata(rqout);
608 pthread_mutex_destroy(rqout->lock);
611 free(server->requests);
614 freebios(server->rbios);
615 free(server->dynamiclookuparg);
617 SSL_free(server->ssl);
619 pthread_mutex_destroy(&server->lock);
620 pthread_cond_destroy(&server->newrq_cond);
621 pthread_mutex_destroy(&server->newrq_mutex);
623 removeclientrqs_sendrq_freeserver_lock(0);
627 int addserver(struct clsrvconf *conf) {
628 struct clsrvconf *res;
633 debug(DBG_ERR, "addserver: currently works with just one server per conf");
636 conf->servers = malloc(sizeof(struct server));
637 if (!conf->servers) {
638 debug(DBG_ERR, "malloc failed");
641 memset(conf->servers, 0, sizeof(struct server));
642 conf->servers->conf = conf;
645 if (type == RAD_DTLS)
646 conf->servers->rbios = newqueue();
648 if (!srcprotores[type]) {
649 res = resolve_hostport(type, *conf->pdef->srcaddrport, NULL);
650 srcprotores[type] = res->addrinfo;
651 res->addrinfo = NULL;
655 conf->servers->sock = -1;
656 if (conf->pdef->addserverextra)
657 conf->pdef->addserverextra(conf);
659 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
660 if (!conf->servers->requests) {
661 debug(DBG_ERR, "malloc failed");
664 for (i = 0; i < MAX_REQUESTS; i++) {
665 conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
666 if (!conf->servers->requests[i].lock) {
667 debug(DBG_ERR, "malloc failed");
670 if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
671 debug(DBG_ERR, "mutex init failed");
672 free(conf->servers->requests[i].lock);
673 conf->servers->requests[i].lock = NULL;
677 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
678 debug(DBG_ERR, "mutex init failed");
681 conf->servers->newrq = 0;
682 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
683 debug(DBG_ERR, "mutex init failed");
684 pthread_mutex_destroy(&conf->servers->lock);
687 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
688 debug(DBG_ERR, "mutex init failed");
689 pthread_mutex_destroy(&conf->servers->newrq_mutex);
690 pthread_mutex_destroy(&conf->servers->lock);
697 freeserver(conf->servers, 0);
698 conf->servers = NULL;
702 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
703 int loc, i, l, n, r = 0;
706 STACK_OF(GENERAL_NAME) *alt;
709 debug(DBG_DBG, "subjectaltnameaddr");
711 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
715 ex = X509_get_ext(cert, loc);
716 alt = X509V3_EXT_d2i(ex);
720 n = sk_GENERAL_NAME_num(alt);
721 for (i = 0; i < n; i++) {
722 gn = sk_GENERAL_NAME_value(alt, i);
723 if (gn->type != GEN_IPADD)
726 v = (char *)ASN1_STRING_data(gn->d.ia5);
727 l = ASN1_STRING_length(gn->d.ia5);
728 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
729 && !memcmp(v, &addr, l)) {
734 GENERAL_NAMES_free(alt);
738 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
745 nm = X509_get_subject_name(cert);
748 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
751 e = X509_NAME_get_entry(nm, loc);
752 t = X509_NAME_ENTRY_get_data(e);
753 v = (char *) ASN1_STRING_data(t);
754 l = ASN1_STRING_length(t);
758 if (l == strlen(exact) && !strncasecmp(exact, v, l))
761 s = stringcopy((char *)v, l);
763 debug(DBG_ERR, "malloc failed");
766 if (regexec(regex, s, 0, NULL, 0)) {
777 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
778 int loc, i, l, n, r = 0;
781 STACK_OF(GENERAL_NAME) *alt;
784 debug(DBG_DBG, "subjectaltnameregexp");
786 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
790 ex = X509_get_ext(cert, loc);
791 alt = X509V3_EXT_d2i(ex);
795 n = sk_GENERAL_NAME_num(alt);
796 for (i = 0; i < n; i++) {
797 gn = sk_GENERAL_NAME_value(alt, i);
798 if (gn->type != type)
801 v = (char *)ASN1_STRING_data(gn->d.ia5);
802 l = ASN1_STRING_length(gn->d.ia5);
806 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
809 if (memcmp(v, exact, l))
812 s = stringcopy((char *)v, l);
814 debug(DBG_ERR, "malloc failed");
817 if (regexec(regex, s, 0, NULL, 0)) {
826 GENERAL_NAMES_free(alt);
830 X509 *verifytlscert(SSL *ssl) {
834 if (SSL_get_verify_result(ssl) != X509_V_OK) {
835 debug(DBG_ERR, "verifytlscert: basic validation failed");
836 while ((error = ERR_get_error()))
837 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
841 cert = SSL_get_peer_certificate(ssl);
843 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
847 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
849 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
850 struct in6_addr addr;
852 if (conf->certnamecheck && conf->prefixlen == 255) {
853 if (inet_pton(AF_INET, conf->host, &addr))
855 else if (inet_pton(AF_INET6, conf->host, &addr))
858 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
861 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
864 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
866 if (!cnregexp(cert, conf->host, NULL)) {
867 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
870 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
873 if (conf->certcnregex) {
874 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
875 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
878 debug(DBG_DBG, "verifyconfcert: CN matching regex");
880 if (conf->certuriregex) {
881 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
882 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
885 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
890 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
892 if (ATTRTYPE(attrs) == type)
894 length -= ATTRLEN(attrs);
895 attrs += ATTRLEN(attrs);
900 struct request *newrqref(struct request *rq) {
906 void freerq(struct request *rq) {
909 debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
912 if (rq->origusername)
913 free(rq->origusername);
919 radmsg_free(rq->msg);
923 void freerqoutdata(struct rqout *rqout) {
931 memset(&rqout->expiry, 0, sizeof(struct timeval));
934 void sendrq(struct request *rq) {
938 removeclientrqs_sendrq_freeserver_lock(1);
943 start = to->conf->statusserver ? 1 : 0;
944 pthread_mutex_lock(&to->newrq_mutex);
945 if (start && rq->msg->code == RAD_Status_Server) {
946 pthread_mutex_lock(to->requests[0].lock);
947 if (to->requests[0].rq) {
948 pthread_mutex_unlock(to->requests[0].lock);
949 debug(DBG_WARN, "sendrq: status server already in queue, dropping request");
956 /* might simplify if only try nextid, might be ok */
957 for (i = to->nextid; i < MAX_REQUESTS; i++) {
958 if (!to->requests[i].rq) {
959 pthread_mutex_lock(to->requests[i].lock);
960 if (!to->requests[i].rq)
962 pthread_mutex_unlock(to->requests[i].lock);
965 if (i == MAX_REQUESTS) {
966 for (i = start; i < to->nextid; i++) {
967 if (!to->requests[i].rq) {
968 pthread_mutex_lock(to->requests[i].lock);
969 if (!to->requests[i].rq)
971 pthread_mutex_unlock(to->requests[i].lock);
974 if (i == to->nextid) {
975 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
980 rq->newid = (uint8_t)i;
981 rq->msg->id = (uint8_t)i;
982 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
984 pthread_mutex_unlock(to->requests[i].lock);
985 debug(DBG_ERR, "sendrq: radmsg2buf failed");
989 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
990 to->requests[i].rq = rq;
991 pthread_mutex_unlock(to->requests[i].lock);
992 if (i >= start) /* i is not reserved for statusserver */
997 debug(DBG_DBG, "sendrq: signalling client writer");
998 pthread_cond_signal(&to->newrq_cond);
1001 pthread_mutex_unlock(&to->newrq_mutex);
1002 removeclientrqs_sendrq_freeserver_lock(0);
1007 rmclientrq(rq, rq->msg->id);
1009 pthread_mutex_unlock(&to->newrq_mutex);
1010 removeclientrqs_sendrq_freeserver_lock(0);
1013 void sendreply(struct request *rq) {
1015 struct client *to = rq->from;
1018 rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
1019 radmsg_free(rq->msg);
1021 if (!rq->replybuf) {
1023 debug(DBG_ERR, "sendreply: radmsg2buf failed");
1027 pthread_mutex_lock(&to->replyq->mutex);
1028 first = list_first(to->replyq->entries) == NULL;
1030 if (!list_push(to->replyq->entries, rq)) {
1031 pthread_mutex_unlock(&to->replyq->mutex);
1033 debug(DBG_ERR, "sendreply: malloc failed");
1038 debug(DBG_DBG, "signalling server writer");
1039 pthread_cond_signal(&to->replyq->cond);
1041 pthread_mutex_unlock(&to->replyq->mutex);
1044 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1045 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1046 static unsigned char first = 1;
1047 static EVP_MD_CTX mdctx;
1048 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1049 unsigned int md_len;
1050 uint8_t i, offset = 0, out[128];
1052 pthread_mutex_lock(&lock);
1054 EVP_MD_CTX_init(&mdctx);
1060 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1061 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1062 !EVP_DigestUpdate(&mdctx, input, 16) ||
1063 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1065 pthread_mutex_unlock(&lock);
1068 for (i = 0; i < 16; i++)
1069 out[offset + i] = hash[i] ^ in[offset + i];
1070 input = out + offset - 16;
1075 memcpy(in, out, len);
1076 pthread_mutex_unlock(&lock);
1080 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1081 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1082 static unsigned char first = 1;
1083 static EVP_MD_CTX mdctx;
1084 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1085 unsigned int md_len;
1086 uint8_t i, offset = 0, out[128];
1088 pthread_mutex_lock(&lock);
1090 EVP_MD_CTX_init(&mdctx);
1096 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1097 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1098 !EVP_DigestUpdate(&mdctx, input, 16) ||
1099 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1101 pthread_mutex_unlock(&lock);
1104 for (i = 0; i < 16; i++)
1105 out[offset + i] = hash[i] ^ in[offset + i];
1106 input = in + offset;
1111 memcpy(in, out, len);
1112 pthread_mutex_unlock(&lock);
1116 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1117 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1118 static unsigned char first = 1;
1119 static EVP_MD_CTX mdctx;
1120 unsigned char hash[EVP_MAX_MD_SIZE];
1121 unsigned int md_len;
1124 pthread_mutex_lock(&lock);
1126 EVP_MD_CTX_init(&mdctx);
1131 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1132 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1133 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1136 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1137 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1138 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1139 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1140 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1141 pthread_mutex_unlock(&lock);
1146 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1149 for (i = 0; i < 16; i++)
1152 for (offset = 16; offset < len; offset += 16) {
1154 printf("text + offset - 16 c(%d): ", offset / 16);
1155 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1157 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1158 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1159 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1160 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1162 pthread_mutex_unlock(&lock);
1166 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1169 for (i = 0; i < 16; i++)
1170 text[offset + i] ^= hash[i];
1174 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1177 pthread_mutex_unlock(&lock);
1181 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1182 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1183 static unsigned char first = 1;
1184 static EVP_MD_CTX mdctx;
1185 unsigned char hash[EVP_MAX_MD_SIZE];
1186 unsigned int md_len;
1190 pthread_mutex_lock(&lock);
1192 EVP_MD_CTX_init(&mdctx);
1197 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1198 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1199 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1202 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1203 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1204 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1205 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1206 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1207 pthread_mutex_unlock(&lock);
1212 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1215 for (i = 0; i < 16; i++)
1216 plain[i] = text[i] ^ hash[i];
1218 for (offset = 16; offset < len; offset += 16) {
1220 printf("text + offset - 16 c(%d): ", offset / 16);
1221 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1223 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1224 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1225 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1226 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1228 pthread_mutex_unlock(&lock);
1232 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1235 for (i = 0; i < 16; i++)
1236 plain[offset + i] = text[offset + i] ^ hash[i];
1239 memcpy(text, plain, len);
1241 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1244 pthread_mutex_unlock(&lock);
1248 struct realm *newrealmref(struct realm *r) {
1254 /* returns with lock on realm */
1255 struct realm *id2realm(struct list *realmlist, char *id) {
1256 struct list_node *entry;
1257 struct realm *realm, *subrealm;
1259 /* need to do locking for subrealms and check subrealm timers */
1260 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1261 realm = (struct realm *)entry->data;
1262 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1263 pthread_mutex_lock(&realm->mutex);
1264 if (realm->subrealms) {
1265 subrealm = id2realm(realm->subrealms, id);
1267 pthread_mutex_unlock(&realm->mutex);
1271 return newrealmref(realm);
1277 /* helper function, only used by removeserversubrealms() */
1278 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1279 struct list_node *entry, *entry2;
1280 struct realm *realm;
1282 for (entry = list_first(realmlist); entry;) {
1283 realm = newrealmref((struct realm *)entry->data);
1284 pthread_mutex_lock(&realm->mutex);
1285 entry = list_next(entry);
1287 if (realm->srvconfs) {
1288 for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
1289 if (entry2->data == srv)
1291 list_removedata(realm->srvconfs, srv);
1292 if (!list_first(realm->srvconfs)) {
1293 list_destroy(realm->srvconfs);
1294 realm->srvconfs = NULL;
1297 if (realm->accsrvconfs) {
1298 for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
1299 if (entry2->data == srv)
1301 list_removedata(realm->accsrvconfs, srv);
1302 if (!list_first(realm->accsrvconfs)) {
1303 list_destroy(realm->accsrvconfs);
1304 realm->accsrvconfs = NULL;
1308 /* remove subrealm if no servers */
1309 if (!realm->srvconfs && !realm->accsrvconfs)
1310 list_removedata(realmlist, realm);
1312 pthread_mutex_unlock(&realm->mutex);
1317 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1318 struct list_node *entry;
1319 struct realm *realm;
1321 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1322 realm = (struct realm *)entry->data;
1323 pthread_mutex_lock(&realm->mutex);
1324 if (realm->subrealms) {
1325 _internal_removeserversubrealms(realm->subrealms, srv);
1326 if (!list_first(realm->subrealms)) {
1327 list_destroy(realm->subrealms);
1328 realm->subrealms = NULL;
1331 pthread_mutex_unlock(&realm->mutex);
1335 int attrvalidate(unsigned char *attrs, int length) {
1336 while (length > 1) {
1337 if (ATTRLEN(attrs) < 2) {
1338 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1341 length -= ATTRLEN(attrs);
1343 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1346 attrs += ATTRLEN(attrs);
1349 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1353 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1354 if (len < 16 || len > 128 || len % 16) {
1355 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1359 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1360 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1364 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1366 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1367 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1373 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1376 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1377 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1380 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
1381 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1387 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1388 char *oldsecret, char *newsecret) {
1389 unsigned char *attr;
1391 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1392 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1393 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
1399 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1403 for (; attrs[0]; attrs += 2)
1404 if (attrs[0] == vendor && attrs[1] == subattr)
1409 /* returns 1 if entire element is to be removed, else 0 */
1410 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
1411 uint8_t alen, sublen;
1415 if (!removevendorattrs)
1418 memcpy(&vendor, attr->v, 4);
1419 vendor = ntohl(vendor);
1420 while (*removevendorattrs && *removevendorattrs != vendor)
1421 removevendorattrs += 2;
1422 if (!*removevendorattrs)
1425 if (findvendorsubattr(removevendorattrs, vendor, -1))
1426 return 1; /* remove entire vendor attribute */
1428 sublen = attr->l - 4;
1429 subattrs = attr->v + 4;
1431 if (!attrvalidate(subattrs, sublen)) {
1432 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1436 while (sublen > 1) {
1437 alen = ATTRLEN(subattrs);
1439 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1440 memmove(subattrs, subattrs + alen, sublen);
1448 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
1449 struct list_node *n, *p;
1453 n = list_first(msg->attrs);
1455 attr = (struct tlv *)n->data;
1456 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
1457 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
1458 list_removedata(msg->attrs, attr);
1460 n = p ? list_next(p) : list_first(msg->attrs);
1467 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
1468 struct list_node *n;
1471 for (n = list_first(addattrs); n; n = list_next(n)) {
1472 a = copytlv((struct tlv *)n->data);
1475 if (!radmsg_add(msg, a)) {
1483 int resizeattr(struct tlv *attr, uint8_t newlen) {
1486 if (newlen != attr->l) {
1487 newv = realloc(attr->v, newlen);
1496 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1497 size_t nmatch = 10, reslen = 0, start = 0;
1498 regmatch_t pmatch[10], *pfield;
1502 in = stringcopy((char *)attr->v, attr->l);
1506 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1511 out = modattr->replacement;
1513 for (i = start; out[i]; i++) {
1514 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1515 pfield = &pmatch[out[i + 1] - '0'];
1516 if (pfield->rm_so >= 0) {
1517 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1523 reslen += i - start;
1525 debug(DBG_WARN, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1530 if (!resizeattr(attr, reslen)) {
1537 for (i = start; out[i]; i++) {
1538 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1539 pfield = &pmatch[out[i + 1] - '0'];
1540 if (pfield->rm_so >= 0) {
1541 memcpy(attr->v + reslen, out + start, i - start);
1542 reslen += i - start;
1543 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1544 reslen += pfield->rm_eo - pfield->rm_so;
1551 memcpy(attr->v + reslen, out + start, i - start);
1555 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1556 struct list_node *n, *m;
1558 for (n = list_first(msg->attrs); n; n = list_next(n))
1559 for (m = list_first(modattrs); m; m = list_next(m))
1560 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1561 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1566 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1569 if (rewrite->removeattrs || rewrite->removevendorattrs)
1570 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1571 if (rewrite->addattrs && !dorewriteadd(msg, rewrite->addattrs))
1573 if (rewrite->modattrs && !dorewritemod(msg, rewrite->modattrs))
1578 int rewriteusername(struct request *rq, struct tlv *attr) {
1579 char *orig = (char *)tlv2str(attr);
1580 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1584 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1585 rq->origusername = (char *)orig;
1591 const char *radmsgtype2string(uint8_t code) {
1592 static const char *rad_msg_names[] = {
1593 "", "Access-Request", "Access-Accept", "Access-Reject",
1594 "Accounting-Request", "Accounting-Response", "", "",
1595 "", "", "", "Access-Challenge",
1596 "Status-Server", "Status-Client"
1598 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1601 void char2hex(char *h, unsigned char c) {
1602 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1603 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1604 h[0] = hexdigits[c / 16];
1605 h[1] = hexdigits[c % 16];
1609 uint8_t *radattr2ascii(struct tlv *attr) {
1617 for (i = 0; i < attr->l; i++)
1618 if (attr->v[i] < 32 || attr->v[i] > 126)
1621 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1628 for (i = 0; i < attr->l; i++)
1629 if (attr->v[i] < 32 || attr->v[i] > 126) {
1631 char2hex((char *)d, attr->v[i]);
1639 void acclog(struct radmsg *msg, char *host) {
1643 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1645 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1648 username = radattr2ascii(attr);
1650 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1655 void respond(struct request *rq, uint8_t code, char *message) {
1659 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1661 debug(DBG_ERR, "respond: malloc failed");
1664 if (message && *message) {
1665 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1666 if (!attr || !radmsg_add(msg, attr)) {
1669 debug(DBG_ERR, "respond: malloc failed");
1674 radmsg_free(rq->msg);
1676 debug(DBG_DBG, "respond: sending %s to %s", radmsgtype2string(msg->code), rq->from->conf->host);
1677 sendreply(newrqref(rq));
1680 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1681 struct list_node *entry;
1682 struct clsrvconf *server, *best = NULL, *first = NULL;
1684 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1685 server = (struct clsrvconf *)entry->data;
1686 if (!server->servers)
1690 if (!server->servers->connectionok)
1692 if (!server->servers->lostrqs)
1698 if (server->servers->lostrqs < best->servers->lostrqs)
1701 return best ? best : first;
1704 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1705 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1706 struct clsrvconf *srvconf;
1707 struct realm *subrealm;
1708 char *id = (char *)tlv2str(username);
1712 /* returns with lock on realm */
1713 *realm = id2realm(realms, id);
1718 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1719 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1724 if (!acc && !(*realm)->parent && !srvconf->servers) {
1725 subrealm = adddynamicrealmserver(*realm, srvconf, id);
1727 pthread_mutex_lock(&subrealm->mutex);
1728 pthread_mutex_unlock(&(*realm)->mutex);
1734 return srvconf->servers;
1738 struct request *newrequest() {
1741 rq = malloc(sizeof(struct request));
1743 debug(DBG_ERR, "newrequest: malloc failed");
1746 memset(rq, 0, sizeof(struct request));
1748 gettimeofday(&rq->created, NULL);
1752 int addclientrq(struct request *rq) {
1756 r = rq->from->rqs[rq->rqid];
1758 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1759 gettimeofday(&now, NULL);
1760 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1762 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1763 sendreply(newrqref(r));
1765 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1771 rq->from->rqs[rq->rqid] = newrqref(rq);
1775 void rmclientrq(struct request *rq, uint8_t id) {
1778 r = rq->from->rqs[id];
1781 rq->from->rqs[id] = NULL;
1785 /* returns 0 if validation/authentication fails, else 1 */
1786 int radsrv(struct request *rq) {
1787 struct radmsg *msg = NULL;
1789 uint8_t *userascii = NULL;
1790 struct realm *realm = NULL;
1791 struct server *to = NULL;
1792 struct client *from = rq->from;
1794 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1799 debug(DBG_WARN, "radsrv: message validation failed, ignoring packet");
1806 memcpy(rq->rqauth, msg->auth, 16);
1808 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1809 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1810 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1814 if (!addclientrq(rq))
1817 if (msg->code == RAD_Status_Server) {
1818 respond(rq, RAD_Access_Accept, NULL);
1822 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1824 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1827 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1829 if (msg->code == RAD_Accounting_Request) {
1830 acclog(msg, from->conf->host);
1831 respond(rq, RAD_Accounting_Response, NULL);
1833 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1837 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1838 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1842 userascii = radattr2ascii(attr);
1845 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1847 /* will return with lock on the realm */
1848 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1850 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1855 if (realm->message && msg->code == RAD_Access_Request) {
1856 debug(DBG_INFO, "radsrv: sending reject to %s for %s", from->conf->host, userascii);
1857 respond(rq, RAD_Access_Reject, realm->message);
1858 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1859 acclog(msg, from->conf->host);
1860 respond(rq, RAD_Accounting_Response, NULL);
1865 if (options.loopprevention && !strcmp(from->conf->name, to->conf->name)) {
1866 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
1867 from->conf->name, to->conf->name);
1871 if (msg->code == RAD_Accounting_Request)
1872 memset(msg->auth, 0, 16);
1873 else if (!RAND_bytes(msg->auth, 16)) {
1874 debug(DBG_WARN, "radsrv: failed to generate random auth");
1879 printfchars(NULL, "auth", "%02x ", auth, 16);
1882 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1884 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1885 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1889 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1891 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1892 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1896 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1902 pthread_mutex_unlock(&realm->mutex);
1907 rmclientrq(rq, msg->id);
1912 pthread_mutex_unlock(&realm->mutex);
1918 void replyh(struct server *server, unsigned char *buf) {
1919 struct client *from;
1920 struct rqout *rqout;
1922 unsigned char *subattrs;
1923 uint8_t *username, *stationid, *replymsg;
1924 struct radmsg *msg = NULL;
1926 struct list_node *node;
1928 server->connectionok = 1;
1929 server->lostrqs = 0;
1931 rqout = server->requests + buf[1];
1932 pthread_mutex_lock(rqout->lock);
1933 if (!rqout->tries) {
1936 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1940 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1944 debug(DBG_WARN, "replyh: message validation failed, ignoring packet");
1947 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1948 && msg->code != RAD_Accounting_Response) {
1949 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1952 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1954 gettimeofday(&server->lastrcv, NULL);
1956 if (rqout->rq->msg->code == RAD_Status_Server) {
1957 freerqoutdata(rqout);
1958 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
1962 gettimeofday(&server->lastreply, NULL);
1963 from = rqout->rq->from;
1965 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1966 debug(DBG_WARN, "replyh: rewritein failed");
1971 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1972 attr = (struct tlv *)node->data;
1973 if (attr->t != RAD_Attr_Vendor_Specific)
1977 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
1980 sublen = attr->l - 4;
1981 subattrs = attr->v + 4;
1982 if (!attrvalidate(subattrs, sublen) ||
1983 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1984 rqout->rq, server->conf->secret, from->conf->secret) ||
1985 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1986 rqout->rq, server->conf->secret, from->conf->secret))
1990 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1994 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1995 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
1997 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
1998 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
2001 debug(DBG_INFO, "%s for user %s stationid %s from %s (%s)",
2002 radmsgtype2string(msg->code), username, stationid, server->conf->host, replymsg);
2005 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2006 radmsgtype2string(msg->code), username, stationid, server->conf->host);
2010 debug(DBG_INFO, "%s for user %s from %s (%s)",
2011 radmsgtype2string(msg->code), username, server->conf->host, replymsg);
2014 debug(DBG_INFO, "%s for user %s from %s",
2015 radmsgtype2string(msg->code), username, server->conf->host);
2021 msg->id = (char)rqout->rq->rqid;
2022 memcpy(msg->auth, rqout->rq->rqauth, 16);
2025 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2028 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
2029 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
2030 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2033 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
2036 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
2037 debug(DBG_WARN, "replyh: rewriteout failed");
2041 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2042 radmsg_free(rqout->rq->msg);
2043 rqout->rq->msg = msg;
2044 sendreply(newrqref(rqout->rq));
2045 freerqoutdata(rqout);
2046 pthread_mutex_unlock(rqout->lock);
2051 pthread_mutex_unlock(rqout->lock);
2055 struct request *createstatsrvrq() {
2062 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
2065 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
2068 if (!radmsg_add(rq->msg, attr)) {
2079 /* code for removing state not finished */
2080 void *clientwr(void *arg) {
2081 struct server *server = (struct server *)arg;
2082 struct rqout *rqout = NULL;
2083 pthread_t clientrdth;
2084 int i, dynconffail = 0;
2087 struct timeval now, laststatsrv;
2088 struct timespec timeout;
2089 struct request *statsrvrq;
2090 struct clsrvconf *conf;
2092 conf = server->conf;
2094 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2099 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2100 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2104 memset(&timeout, 0, sizeof(struct timespec));
2106 if (conf->statusserver) {
2107 gettimeofday(&server->lastrcv, NULL);
2108 gettimeofday(&laststatsrv, NULL);
2111 if (conf->pdef->connecter) {
2112 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2114 server->connectionok = 1;
2115 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
2116 debug(DBG_ERR, "clientwr: pthread_create failed");
2120 server->connectionok = 1;
2123 pthread_mutex_lock(&server->newrq_mutex);
2124 if (!server->newrq) {
2125 gettimeofday(&now, NULL);
2126 /* random 0-7 seconds */
2127 RAND_bytes(&rnd, 1);
2129 if (conf->statusserver) {
2130 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2131 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
2133 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
2134 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
2136 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2137 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2140 if (timeout.tv_sec > now.tv_sec)
2141 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2143 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2146 if (server->newrq) {
2147 debug(DBG_DBG, "clientwr: got new request");
2152 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2154 pthread_mutex_unlock(&server->newrq_mutex);
2156 for (i = 0; i < MAX_REQUESTS; i++) {
2157 if (server->clientrdgone) {
2158 pthread_join(clientrdth, NULL);
2162 for (; i < MAX_REQUESTS; i++) {
2163 rqout = server->requests + i;
2165 pthread_mutex_lock(rqout->lock);
2168 pthread_mutex_unlock(rqout->lock);
2172 if (i == MAX_REQUESTS)
2175 gettimeofday(&now, NULL);
2176 if (now.tv_sec < rqout->expiry.tv_sec) {
2177 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2178 timeout.tv_sec = rqout->expiry.tv_sec;
2179 pthread_mutex_unlock(rqout->lock);
2183 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2184 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2185 if (conf->statusserver) {
2186 if (*rqout->rq->buf == RAD_Status_Server) {
2187 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2188 if (server->lostrqs < 255)
2192 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2193 if (server->lostrqs < 255)
2196 freerqoutdata(rqout);
2197 pthread_mutex_unlock(rqout->lock);
2201 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2202 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2203 timeout.tv_sec = rqout->expiry.tv_sec;
2205 conf->pdef->clientradput(server, rqout->rq->buf);
2206 pthread_mutex_unlock(rqout->lock);
2208 if (conf->statusserver && server->connectionok) {
2209 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2210 gettimeofday(&now, NULL);
2211 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
2213 statsrvrq = createstatsrvrq();
2215 statsrvrq->to = server;
2216 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2223 conf->servers = NULL;
2224 if (server->dynamiclookuparg) {
2225 removeserversubrealms(realms, conf);
2229 freeclsrvconf(conf);
2231 freeserver(server, 1);
2232 ERR_remove_state(0);
2236 void createlistener(uint8_t type, char *arg) {
2238 struct clsrvconf *listenres;
2239 struct addrinfo *res;
2240 int s = -1, on = 1, *sp = NULL;
2242 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2244 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2246 for (res = listenres->addrinfo; res; res = res->ai_next) {
2247 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2249 debug(DBG_WARN, "createlistener: socket failed");
2252 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2254 if (res->ai_family == AF_INET6)
2255 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2257 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2258 debug(DBG_WARN, "createlistener: bind failed");
2264 sp = malloc(sizeof(int));
2266 debugx(1, DBG_ERR, "malloc failed");
2268 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
2269 debugx(1, DBG_ERR, "pthread_create failed");
2273 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2275 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
2276 listenres->host ? listenres->host : "*", listenres->port);
2277 freeclsrvres(listenres);
2280 void createlisteners(uint8_t type, char **args) {
2284 for (i = 0; args[i]; i++)
2285 createlistener(type, args[i]);
2287 createlistener(type, NULL);
2291 void ssl_info_callback(const SSL *ssl, int where, int ret) {
2295 w = where & ~SSL_ST_MASK;
2297 if (w & SSL_ST_CONNECT)
2299 else if (w & SSL_ST_ACCEPT)
2304 if (where & SSL_CB_LOOP)
2305 debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
2306 else if (where & SSL_CB_ALERT) {
2307 s = (where & SSL_CB_READ) ? "read" : "write";
2308 debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
2310 else if (where & SSL_CB_EXIT) {
2312 debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
2314 debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
2324 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2325 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2326 for (i = 0; i < CRYPTO_num_locks(); i++) {
2327 ssl_lock_count[i] = 0;
2328 pthread_mutex_init(&ssl_locks[i], NULL);
2330 CRYPTO_set_id_callback(ssl_thread_id);
2331 CRYPTO_set_locking_callback(ssl_locking_callback);
2333 SSL_load_error_strings();
2336 while (!RAND_status()) {
2339 RAND_seed((unsigned char *)&t, sizeof(time_t));
2340 RAND_seed((unsigned char *)&pid, sizeof(pid));
2344 int tlsaddcacrl(SSL_CTX *ctx, struct tls *conf) {
2345 STACK_OF(X509_NAME) *calist;
2347 unsigned long error;
2349 if (!SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2350 while ((error = ERR_get_error()))
2351 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2352 debug(DBG_ERR, "tlsaddcacrl: Error updating TLS context %s", conf->name);
2356 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2357 if (!conf->cacertfile || calist) {
2358 if (conf->cacertpath) {
2360 calist = sk_X509_NAME_new_null();
2361 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2362 sk_X509_NAME_free(calist);
2368 while ((error = ERR_get_error()))
2369 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2370 debug(DBG_ERR, "tlsaddcacrl: Error adding CA subjects in TLS context %s", conf->name);
2373 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2374 SSL_CTX_set_client_CA_list(ctx, calist);
2376 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2377 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2379 if (conf->crlcheck) {
2380 x509_s = SSL_CTX_get_cert_store(ctx);
2381 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2384 debug(DBG_DBG, "tlsaddcacrl: updated TLS context %s", conf->name);
2388 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2389 SSL_CTX *ctx = NULL;
2390 unsigned long error;
2397 ctx = SSL_CTX_new(TLSv1_method());
2399 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2403 ctx = SSL_CTX_new(DTLSv1_method());
2405 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2407 SSL_CTX_set_read_ahead(ctx, 1);
2411 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2415 if (conf->certkeypwd) {
2416 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2417 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2419 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2420 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2421 !SSL_CTX_check_private_key(ctx)) {
2422 while ((error = ERR_get_error()))
2423 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2424 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2429 if (!tlsaddcacrl(ctx, conf)) {
2434 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
2438 struct tls *tlsgettls(char *alt1, char *alt2) {
2441 t = hash_read(tlsconfs, alt1, strlen(alt1));
2443 t = hash_read(tlsconfs, alt2, strlen(alt2));
2447 SSL_CTX *tlsgetctx(uint8_t type, struct tls *t) {
2452 gettimeofday(&now, NULL);
2456 if (t->tlsexpiry && t->tlsctx) {
2457 if (t->tlsexpiry < now.tv_sec) {
2458 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
2459 tlsaddcacrl(t->tlsctx, t);
2463 t->tlsctx = tlscreatectx(RAD_TLS, t);
2465 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
2469 if (t->dtlsexpiry && t->dtlsctx) {
2470 if (t->dtlsexpiry < now.tv_sec) {
2471 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
2472 tlsaddcacrl(t->dtlsctx, t);
2476 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2478 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
2485 struct list *addsrvconfs(char *value, char **names) {
2486 struct list *conflist;
2488 struct list_node *entry;
2489 struct clsrvconf *conf = NULL;
2491 if (!names || !*names)
2494 conflist = list_create();
2496 debug(DBG_ERR, "malloc failed");
2500 for (n = 0; names[n]; n++) {
2501 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2502 conf = (struct clsrvconf *)entry->data;
2503 if (!strcasecmp(names[n], conf->name))
2507 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2508 list_destroy(conflist);
2511 if (!list_push(conflist, conf)) {
2512 debug(DBG_ERR, "malloc failed");
2513 list_destroy(conflist);
2516 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2521 void freerealm(struct realm *realm) {
2524 debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2525 if (--realm->refcount)
2529 free(realm->message);
2530 regfree(&realm->regex);
2531 pthread_mutex_destroy(&realm->mutex);
2532 /* if refcount == 0, all subrealms gone */
2533 list_destroy(realm->subrealms);
2534 /* if refcount == 0, all srvconfs gone */
2535 list_destroy(realm->srvconfs);
2536 /* if refcount == 0, all accsrvconfs gone */
2537 list_destroy(realm->accsrvconfs);
2538 freerealm(realm->parent);
2542 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2544 struct realm *realm;
2545 char *s, *regex = NULL;
2547 if (*value == '/') {
2548 /* regexp, remove optional trailing / if present */
2549 if (value[strlen(value) - 1] == '/')
2550 value[strlen(value) - 1] = '\0';
2552 /* not a regexp, let us make it one */
2553 if (*value == '*' && !value[1])
2554 regex = stringcopy(".*", 0);
2556 for (n = 0, s = value; *s;)
2559 regex = malloc(strlen(value) + n + 3);
2562 for (n = 1, s = value; *s; s++) {
2572 debug(DBG_ERR, "malloc failed");
2576 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2579 realm = malloc(sizeof(struct realm));
2581 debug(DBG_ERR, "malloc failed");
2584 memset(realm, 0, sizeof(struct realm));
2586 if (pthread_mutex_init(&realm->mutex, NULL)) {
2587 debug(DBG_ERR, "mutex init failed");
2593 realm->name = stringcopy(value, 0);
2595 debug(DBG_ERR, "malloc failed");
2598 if (message && strlen(message) > 253) {
2599 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2602 realm->message = message;
2603 realm->accresp = accresp;
2605 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2606 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2610 if (servers && *servers) {
2611 realm->srvconfs = addsrvconfs(value, servers);
2612 if (!realm->srvconfs)
2616 if (accservers && *accservers) {
2617 realm->accsrvconfs = addsrvconfs(value, accservers);
2618 if (!realm->accsrvconfs)
2622 if (!list_push(realmlist, realm)) {
2623 debug(DBG_ERR, "malloc failed");
2624 pthread_mutex_destroy(&realm->mutex);
2628 debug(DBG_DBG, "addrealm: added realm %s", value);
2632 while (list_shift(realm->srvconfs));
2633 while (list_shift(realm->accsrvconfs));
2640 for (n = 0; servers[n]; n++)
2642 for (n = 0; servers[n]; n++)
2648 for (n = 0; accservers[n]; n++)
2650 for (n = 0; accservers[n]; n++)
2651 free(accservers[n]);
2654 return newrealmref(realm);
2657 struct realm *adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2658 struct clsrvconf *srvconf;
2659 struct realm *newrealm = NULL;
2660 char *realmname, *s;
2663 if (!conf->dynamiclookupcommand)
2666 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2667 realmname = strrchr(id, '@');
2673 for (s = realmname; *s; s++)
2674 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2677 srvconf = malloc(sizeof(struct clsrvconf));
2679 debug(DBG_ERR, "malloc failed");
2683 if (!addserver(srvconf))
2686 if (!realm->subrealms)
2687 realm->subrealms = list_create();
2688 if (!realm->subrealms)
2690 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2693 newrealm->parent = newrealmref(realm);
2695 /* add server and accserver to newrealm */
2696 newrealm->srvconfs = list_create();
2697 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2698 debug(DBG_ERR, "malloc failed");
2701 newrealmref(newrealm);
2702 newrealm->accsrvconfs = list_create();
2703 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2704 debug(DBG_ERR, "malloc failed");
2705 list_shift(realm->srvconfs);
2706 freerealm(newrealm);
2709 newrealmref(newrealm);
2711 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2712 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2713 debug(DBG_ERR, "pthread_create failed");
2714 list_shift(realm->srvconfs);
2715 freerealm(newrealm);
2716 list_shift(realm->accsrvconfs);
2717 freerealm(newrealm);
2720 pthread_detach(clientth);
2725 list_removedata(realm->subrealms, newrealm);
2726 freerealm(newrealm);
2727 if (!list_first(realm->subrealms)) {
2728 list_destroy(realm->subrealms);
2729 realm->subrealms = NULL;
2732 freeserver(srvconf->servers, 1);
2734 debug(DBG_ERR, "failed to create dynamic server");
2738 int dynamicconfig(struct server *server) {
2739 int ok, fd[2], status;
2741 struct clsrvconf *conf = server->conf;
2742 struct gconffile *cf = NULL;
2744 /* for now we only learn hostname/address */
2745 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2748 debug(DBG_ERR, "dynamicconfig: pipe error");
2753 debug(DBG_ERR, "dynamicconfig: fork error");
2757 } else if (pid == 0) {
2760 if (fd[1] != STDOUT_FILENO) {
2761 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2762 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2765 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2766 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2770 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2771 ok = getgenericconfig(&cf, NULL,
2772 "Server", CONF_CBK, confserver_cb, (void *)conf,
2777 if (waitpid(pid, &status, 0) < 0) {
2778 debug(DBG_ERR, "dynamicconfig: wait error");
2783 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2791 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2795 int addmatchcertattr(struct clsrvconf *conf) {
2799 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2800 r = &conf->certcnregex;
2801 v = conf->matchcertattr + 4;
2802 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2803 r = &conf->certuriregex;
2804 v = conf->matchcertattr + 20;
2809 /* regexp, remove optional trailing / if present */
2810 if (v[strlen(v) - 1] == '/')
2811 v[strlen(v) - 1] = '\0';
2815 *r = malloc(sizeof(regex_t));
2817 debug(DBG_ERR, "malloc failed");
2820 if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2823 debug(DBG_ERR, "failed to compile regular expression %s", v);
2829 /* should accept both names and numeric values, only numeric right now */
2830 uint8_t attrname2val(char *attrname) {
2833 val = atoi(attrname);
2834 return val > 0 && val < 256 ? val : 0;
2837 /* should accept both names and numeric values, only numeric right now */
2838 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2841 *vendor = atoi(attrname);
2842 s = strchr(attrname, ':');
2847 *type = atoi(s + 1);
2848 return *type >= 0 && *type < 256;
2851 /* should accept both names and numeric values, only numeric right now */
2852 struct tlv *extractattr(char *nameval) {
2857 s = strchr(nameval, ':');
2858 name = atoi(nameval);
2859 if (!s || name < 1 || name > 255)
2861 len = strlen(s + 1);
2864 a = malloc(sizeof(struct tlv));
2867 a->v = (uint8_t *)stringcopy(s + 1, 0);
2877 /* should accept both names and numeric values, only numeric right now */
2878 struct modattr *extractmodattr(char *nameval) {
2883 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2887 s = strchr(nameval, ':');
2888 name = atoi(nameval);
2889 if (!s || name < 1 || name > 255 || s[1] != '/')
2893 /* regexp, remove optional trailing / if present */
2894 if (s[strlen(s) - 1] == '/')
2895 s[strlen(s) - 1] = '\0';
2903 m = malloc(sizeof(struct modattr));
2905 debug(DBG_ERR, "malloc failed");
2910 m->replacement = stringcopy(t, 0);
2911 if (!m->replacement) {
2913 debug(DBG_ERR, "malloc failed");
2917 m->regex = malloc(sizeof(regex_t));
2919 free(m->replacement);
2921 debug(DBG_ERR, "malloc failed");
2925 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2927 free(m->replacement);
2929 debug(DBG_ERR, "failed to compile regular expression %s", s);
2936 struct rewrite *getrewrite(char *alt1, char *alt2) {
2939 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2941 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2946 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
2947 struct rewrite *rewrite = NULL;
2949 uint8_t *rma = NULL;
2950 uint32_t *p, *rmva = NULL;
2951 struct list *adda = NULL, *moda = NULL;
2956 for (n = 0; rmattrs[n]; n++);
2957 rma = calloc(n + 1, sizeof(uint8_t));
2959 debugx(1, DBG_ERR, "malloc failed");
2961 for (i = 0; i < n; i++) {
2962 if (!(rma[i] = attrname2val(rmattrs[i])))
2963 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
2971 for (n = 0; rmvattrs[n]; n++);
2972 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2974 debugx(1, DBG_ERR, "malloc failed");
2976 for (p = rmva, i = 0; i < n; i++, p += 2) {
2977 if (!vattrname2val(rmvattrs[i], p, p + 1))
2978 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
2986 adda = list_create();
2988 debugx(1, DBG_ERR, "malloc failed");
2989 for (i = 0; addattrs[i]; i++) {
2990 a = extractattr(addattrs[i]);
2992 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
2994 if (!list_push(adda, a))
2995 debugx(1, DBG_ERR, "malloc failed");
3001 moda = list_create();
3003 debugx(1, DBG_ERR, "malloc failed");
3004 for (i = 0; modattrs[i]; i++) {
3005 m = extractmodattr(modattrs[i]);
3007 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
3009 if (!list_push(moda, m))
3010 debugx(1, DBG_ERR, "malloc failed");
3015 if (rma || rmva || adda || moda) {
3016 rewrite = malloc(sizeof(struct rewrite));
3018 debugx(1, DBG_ERR, "malloc failed");
3019 rewrite->removeattrs = rma;
3020 rewrite->removevendorattrs = rmva;
3021 rewrite->addattrs = adda;
3022 rewrite->modattrs = moda;
3025 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
3026 debugx(1, DBG_ERR, "malloc failed");
3027 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3030 void freeclsrvconf(struct clsrvconf *conf) {
3036 free(conf->matchcertattr);
3037 if (conf->certcnregex)
3038 regfree(conf->certcnregex);
3039 if (conf->certuriregex)
3040 regfree(conf->certuriregex);
3041 free(conf->confrewritein);
3042 free(conf->confrewriteout);
3043 if (conf->rewriteusername) {
3044 if (conf->rewriteusername->regex)
3045 regfree(conf->rewriteusername->regex);
3046 free(conf->rewriteusername->replacement);
3047 free(conf->rewriteusername);
3049 free(conf->dynamiclookupcommand);
3050 free(conf->rewritein);
3051 free(conf->rewriteout);
3053 freeaddrinfo(conf->addrinfo);
3055 pthread_mutex_destroy(conf->lock);
3058 /* not touching ssl_ctx, clients and servers */
3062 int mergeconfstring(char **dst, char **src) {
3071 t = stringcopy(*dst, 0);
3073 debug(DBG_ERR, "malloc failed");
3081 /* assumes dst is a shallow copy */
3082 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3083 if (!mergeconfstring(&dst->name, &src->name) ||
3084 !mergeconfstring(&dst->host, &src->host) ||
3085 !mergeconfstring(&dst->port, &src->port) ||
3086 !mergeconfstring(&dst->secret, &src->secret) ||
3087 !mergeconfstring(&dst->tls, &src->tls) ||
3088 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3089 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
3090 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
3091 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3094 dst->pdef = src->pdef;
3095 dst->statusserver = src->statusserver;
3096 dst->certnamecheck = src->certnamecheck;
3097 if (src->retryinterval != 255)
3098 dst->retryinterval = src->retryinterval;
3099 if (src->retrycount != 255)
3100 dst->retrycount = src->retrycount;
3104 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3105 struct clsrvconf *conf;
3106 char *conftype = NULL, *rewriteinalias = NULL;
3107 long int dupinterval = LONG_MIN;
3109 debug(DBG_DBG, "confclient_cb called for %s", block);
3111 conf = malloc(sizeof(struct clsrvconf));
3113 debugx(1, DBG_ERR, "malloc failed");
3114 memset(conf, 0, sizeof(struct clsrvconf));
3115 conf->certnamecheck = 1;
3117 if (!getgenericconfig(cf, block,
3118 "type", CONF_STR, &conftype,
3119 "host", CONF_STR, &conf->host,
3120 "secret", CONF_STR, &conf->secret,
3121 "tls", CONF_STR, &conf->tls,
3122 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3123 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3124 "DuplicateInterval", CONF_LINT, &dupinterval,
3125 "rewrite", CONF_STR, &rewriteinalias,
3126 "rewriteIn", CONF_STR, &conf->confrewritein,
3127 "rewriteOut", CONF_STR, &conf->confrewriteout,
3128 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
3131 debugx(1, DBG_ERR, "configuration error");
3133 conf->name = stringcopy(val, 0);
3135 conf->host = stringcopy(val, 0);
3136 if (!conf->name || !conf->host)
3137 debugx(1, DBG_ERR, "malloc failed");
3140 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3141 conf->type = protoname2int(conftype);
3142 conf->pdef = &protodefs[conf->type];
3143 if (!conf->pdef->name)
3144 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3147 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3148 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
3150 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3151 if (conf->matchcertattr && !addmatchcertattr(conf))
3152 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3155 if (dupinterval != LONG_MIN) {
3156 if (dupinterval < 0 || dupinterval > 255)
3157 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
3158 conf->dupinterval = (uint8_t)dupinterval;
3160 conf->dupinterval = conf->pdef->duplicateintervaldefault;
3162 if (!conf->confrewritein)
3163 conf->confrewritein = rewriteinalias;
3165 free(rewriteinalias);
3166 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
3167 if (conf->confrewriteout)
3168 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3170 if (conf->confrewriteusername) {
3171 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
3172 if (!conf->rewriteusername)
3173 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3176 if (!resolvepeer(conf, 0))
3177 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3179 if (!conf->secret) {
3180 if (!conf->pdef->secretdefault)
3181 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3182 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3184 debugx(1, DBG_ERR, "malloc failed");
3187 conf->lock = malloc(sizeof(pthread_mutex_t));
3189 debugx(1, DBG_ERR, "malloc failed");
3191 pthread_mutex_init(conf->lock, NULL);
3192 if (!list_push(clconfs, conf))
3193 debugx(1, DBG_ERR, "malloc failed");
3197 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3198 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3199 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
3200 if (!conf->tlsconf) {
3201 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3204 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3205 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3211 conf->port = stringcopy(conf->pdef->portdefault, 0);
3213 debug(DBG_ERR, "malloc failed");
3218 if (conf->retryinterval == 255)
3219 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3220 if (conf->retrycount == 255)
3221 conf->retrycount = protodefs[conf->type].retrycountdefault;
3223 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
3224 if (conf->confrewriteout)
3225 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3227 if (!conf->secret) {
3228 if (!conf->pdef->secretdefault) {
3229 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3232 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3233 if (!conf->secret) {
3234 debug(DBG_ERR, "malloc failed");
3239 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3240 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3246 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3247 struct clsrvconf *conf, *resconf;
3248 char *conftype = NULL, *rewriteinalias = NULL;
3249 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3251 debug(DBG_DBG, "confserver_cb called for %s", block);
3253 conf = malloc(sizeof(struct clsrvconf));
3255 debug(DBG_ERR, "malloc failed");
3258 memset(conf, 0, sizeof(struct clsrvconf));
3259 resconf = (struct clsrvconf *)arg;
3261 conf->statusserver = resconf->statusserver;
3262 conf->certnamecheck = resconf->certnamecheck;
3264 conf->certnamecheck = 1;
3266 if (!getgenericconfig(cf, block,
3267 "type", CONF_STR, &conftype,
3268 "host", CONF_STR, &conf->host,
3269 "port", CONF_STR, &conf->port,
3270 "secret", CONF_STR, &conf->secret,
3271 "tls", CONF_STR, &conf->tls,
3272 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3273 "rewrite", CONF_STR, &rewriteinalias,
3274 "rewriteIn", CONF_STR, &conf->confrewritein,
3275 "rewriteOut", CONF_STR, &conf->confrewriteout,
3276 "StatusServer", CONF_BLN, &conf->statusserver,
3277 "RetryInterval", CONF_LINT, &retryinterval,
3278 "RetryCount", CONF_LINT, &retrycount,
3279 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3280 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3283 debug(DBG_ERR, "configuration error");
3287 conf->name = stringcopy(val, 0);
3289 debug(DBG_ERR, "malloc failed");
3293 conf->host = stringcopy(val, 0);
3295 debug(DBG_ERR, "malloc failed");
3301 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3302 conf->type = protoname2int(conftype);
3303 conf->pdef = &protodefs[conf->type];
3304 if (!conf->pdef->name) {
3305 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3311 if (!conf->confrewritein)
3312 conf->confrewritein = rewriteinalias;
3314 free(rewriteinalias);
3315 rewriteinalias = NULL;
3317 if (retryinterval != LONG_MIN) {
3318 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3319 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3322 conf->retryinterval = (uint8_t)retryinterval;
3324 conf->retryinterval = 255;
3326 if (retrycount != LONG_MIN) {
3327 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3328 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3331 conf->retrycount = (uint8_t)retrycount;
3333 conf->retrycount = 255;
3336 if (!mergesrvconf(resconf, conf))
3340 if (conf->dynamiclookupcommand) {
3341 free(conf->dynamiclookupcommand);
3342 conf->dynamiclookupcommand = NULL;
3346 if (resconf || !conf->dynamiclookupcommand) {
3347 if (!compileserverconfig(conf, block))
3354 if (!list_push(srvconfs, conf)) {
3355 debug(DBG_ERR, "malloc failed");
3362 free(rewriteinalias);
3363 freeclsrvconf(conf);
3367 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3368 char **servers = NULL, **accservers = NULL, *msg = NULL;
3369 uint8_t accresp = 0;
3371 debug(DBG_DBG, "confrealm_cb called for %s", block);
3373 if (!getgenericconfig(cf, block,
3374 "server", CONF_MSTR, &servers,
3375 "accountingServer", CONF_MSTR, &accservers,
3376 "ReplyMessage", CONF_STR, &msg,
3377 "AccountingResponse", CONF_BLN, &accresp,
3380 debugx(1, DBG_ERR, "configuration error");
3382 addrealm(realms, val, servers, accservers, msg, accresp);
3386 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3388 long int expiry = LONG_MIN;
3390 debug(DBG_DBG, "conftls_cb called for %s", block);
3392 conf = malloc(sizeof(struct tls));
3394 debug(DBG_ERR, "conftls_cb: malloc failed");
3397 memset(conf, 0, sizeof(struct tls));
3399 if (!getgenericconfig(cf, block,
3400 "CACertificateFile", CONF_STR, &conf->cacertfile,
3401 "CACertificatePath", CONF_STR, &conf->cacertpath,
3402 "CertificateFile", CONF_STR, &conf->certfile,
3403 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3404 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3405 "CacheExpiry", CONF_LINT, &expiry,
3406 "CRLCheck", CONF_BLN, &conf->crlcheck,
3409 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3412 if (!conf->certfile || !conf->certkeyfile) {
3413 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3416 if (!conf->cacertfile && !conf->cacertpath) {
3417 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3420 if (expiry != LONG_MIN) {
3422 debug(DBG_ERR, "error in block %s, value of option CacheExpiry is %ld, may not be negative", val, expiry);
3425 conf->cacheexpiry = expiry;
3428 conf->name = stringcopy(val, 0);
3430 debug(DBG_ERR, "conftls_cb: malloc failed");
3434 if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
3435 debug(DBG_ERR, "conftls_cb: malloc failed");
3438 if (!tlsgetctx(RAD_TLS, conf))
3439 debug(DBG_ERR, "conftls_cb: error creating ctx for TLS block %s", val);
3440 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3444 free(conf->cacertfile);
3445 free(conf->cacertpath);
3446 free(conf->certfile);
3447 free(conf->certkeyfile);
3448 free(conf->certkeypwd);
3453 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3454 char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3456 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3458 if (!getgenericconfig(cf, block,
3459 "removeAttribute", CONF_MSTR, &rmattrs,
3460 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3461 "addAttribute", CONF_MSTR, &addattrs,
3462 "modifyAttribute", CONF_MSTR, &modattrs,
3465 debugx(1, DBG_ERR, "configuration error");
3466 addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3470 void getmainconfig(const char *configfile) {
3471 long int loglevel = LONG_MIN;
3472 struct gconffile *cfs;
3474 cfs = openconfigfile(configfile);
3475 memset(&options, 0, sizeof(options));
3477 clconfs = list_create();
3479 debugx(1, DBG_ERR, "malloc failed");
3481 srvconfs = list_create();
3483 debugx(1, DBG_ERR, "malloc failed");
3485 realms = list_create();
3487 debugx(1, DBG_ERR, "malloc failed");
3489 tlsconfs = hash_create();
3491 debugx(1, DBG_ERR, "malloc failed");
3493 rewriteconfs = hash_create();
3495 debugx(1, DBG_ERR, "malloc failed");
3497 if (!getgenericconfig(&cfs, NULL,
3498 "ListenUDP", CONF_MSTR, &options.listenudp,
3499 "ListenTCP", CONF_MSTR, &options.listentcp,
3500 "ListenTLS", CONF_MSTR, &options.listentls,
3501 "ListenDTLS", CONF_MSTR, &options.listendtls,
3502 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
3503 "SourceUDP", CONF_STR, &options.sourceudp,
3504 "SourceTCP", CONF_STR, &options.sourcetcp,
3505 "SourceTLS", CONF_STR, &options.sourcetls,
3506 "SourceDTLS", CONF_STR, &options.sourcedtls,
3507 "LogLevel", CONF_LINT, &loglevel,
3508 "LogDestination", CONF_STR, &options.logdestination,
3509 "LoopPrevention", CONF_BLN, &options.loopprevention,
3510 "Client", CONF_CBK, confclient_cb, NULL,
3511 "Server", CONF_CBK, confserver_cb, NULL,
3512 "Realm", CONF_CBK, confrealm_cb, NULL,
3513 "TLS", CONF_CBK, conftls_cb, NULL,
3514 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3517 debugx(1, DBG_ERR, "configuration error");
3519 if (loglevel != LONG_MIN) {
3520 if (loglevel < 1 || loglevel > 4)
3521 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3522 options.loglevel = (uint8_t)loglevel;
3526 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3529 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3532 *configfile = optarg;
3535 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3536 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3537 *loglevel = *optarg - '0';
3546 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3551 if (!(argc - optind))
3555 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3559 int daemon(int a, int b) {
3567 for (i = 0; i < 3; i++) {
3569 open("/dev/null", O_RDWR);
3575 void *sighandler(void *arg) {
3580 sigemptyset(&sigset);
3581 sigaddset(&sigset, SIGPIPE);
3582 sigwait(&sigset, &sig);
3583 /* only get SIGPIPE right now, so could simplify below code */
3586 /* completely ignoring this */
3589 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3592 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3597 int main(int argc, char **argv) {
3600 struct list_node *entry;
3601 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3602 char *configfile = NULL;
3603 struct clsrvconf *srvconf;
3606 debug_init("radsecproxy");
3607 debug_set_level(DEBUG_LEVEL);
3609 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3611 debug_set_level(loglevel);
3612 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3614 options.loglevel = loglevel;
3615 else if (options.loglevel)
3616 debug_set_level(options.loglevel);
3618 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3619 free(options.logdestination);
3621 if (!list_first(clconfs))
3622 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3623 if (!list_first(realms))
3624 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3627 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3629 if (!foreground && (daemon(0, 0) < 0))
3630 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3632 debug_timestamp_on();
3633 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3635 sigemptyset(&sigset);
3636 /* exit on all but SIGPIPE, ignore more? */
3637 sigaddset(&sigset, SIGPIPE);
3638 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3639 pthread_create(&sigth, NULL, sighandler, NULL);
3641 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3642 srvconf = (struct clsrvconf *)entry->data;
3643 if (srvconf->dynamiclookupcommand)
3645 if (!addserver(srvconf))
3646 debugx(1, DBG_ERR, "failed to add server");
3647 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3648 (void *)(srvconf->servers)))
3649 debugx(1, DBG_ERR, "pthread_create failed");
3651 /* srcprotores for UDP no longer needed */
3652 if (srcprotores[RAD_UDP]) {
3653 freeaddrinfo(srcprotores[RAD_UDP]);
3654 srcprotores[RAD_UDP] = NULL;
3657 for (i = 0; protodefs[i].name; i++)
3658 if (protodefs[i].initextra)
3659 protodefs[i].initextra();
3661 if (find_clconf_type(RAD_TCP, NULL))
3662 createlisteners(RAD_TCP, options.listentcp);
3664 if (find_clconf_type(RAD_TLS, NULL))
3665 createlisteners(RAD_TLS, options.listentls);
3667 if (find_clconf_type(RAD_DTLS, NULL))
3668 createlisteners(RAD_DTLS, options.listendtls);
3670 if (find_clconf_type(RAD_UDP, NULL)) {
3671 createlisteners(RAD_UDP, options.listenudp);
3672 if (options.listenaccudp)
3673 createlisteners(RAD_UDP, options.listenaccudp);
3676 /* just hang around doing nothing, anything to do here? */