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 * We are not removing client requests from dynamic servers, see removeclientrqs()
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 void 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(struct client *client) {
552 for (i = 0; i < MAX_REQUESTS; i++) {
556 rqout = rq->to->requests + rq->newid;
557 pthread_mutex_lock(rqout->lock);
558 if (rqout->rq == rq) /* still pointing to our request */
559 freerqoutdata(rqout);
560 pthread_mutex_unlock(rqout->lock);
565 void removeclient(struct client *client) {
566 struct clsrvconf *conf;
571 pthread_mutex_lock(conf->lock);
573 removeclientrqs(client);
574 removequeue(client->replyq);
575 list_removedata(conf->clients, client);
579 pthread_mutex_unlock(conf->lock);
582 void freeserver(struct server *server, uint8_t destroymutex) {
583 struct rqout *rqout, *end;
588 if (server->requests) {
589 rqout = server->requests;
590 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
591 freerqoutdata(rqout);
592 pthread_mutex_destroy(rqout->lock);
595 free(server->requests);
598 freebios(server->rbios);
599 free(server->dynamiclookuparg);
601 SSL_free(server->ssl);
603 pthread_mutex_destroy(&server->lock);
604 pthread_cond_destroy(&server->newrq_cond);
605 pthread_mutex_destroy(&server->newrq_mutex);
610 int addserver(struct clsrvconf *conf) {
611 struct clsrvconf *res;
616 debug(DBG_ERR, "addserver: currently works with just one server per conf");
619 conf->servers = malloc(sizeof(struct server));
620 if (!conf->servers) {
621 debug(DBG_ERR, "malloc failed");
624 memset(conf->servers, 0, sizeof(struct server));
625 conf->servers->conf = conf;
628 if (type == RAD_DTLS)
629 conf->servers->rbios = newqueue();
631 if (!srcprotores[type]) {
632 res = resolve_hostport(type, *conf->pdef->srcaddrport, NULL);
633 srcprotores[type] = res->addrinfo;
634 res->addrinfo = NULL;
638 conf->servers->sock = -1;
639 if (conf->pdef->addserverextra)
640 conf->pdef->addserverextra(conf);
642 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
643 if (!conf->servers->requests) {
644 debug(DBG_ERR, "malloc failed");
647 for (i = 0; i < MAX_REQUESTS; i++) {
648 conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
649 if (!conf->servers->requests[i].lock) {
650 debug(DBG_ERR, "malloc failed");
653 if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
654 debug(DBG_ERR, "mutex init failed");
655 free(conf->servers->requests[i].lock);
656 conf->servers->requests[i].lock = NULL;
660 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
661 debug(DBG_ERR, "mutex init failed");
664 conf->servers->newrq = 0;
665 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
666 debug(DBG_ERR, "mutex init failed");
667 pthread_mutex_destroy(&conf->servers->lock);
670 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
671 debug(DBG_ERR, "mutex init failed");
672 pthread_mutex_destroy(&conf->servers->newrq_mutex);
673 pthread_mutex_destroy(&conf->servers->lock);
680 freeserver(conf->servers, 0);
681 conf->servers = NULL;
685 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
686 int loc, i, l, n, r = 0;
689 STACK_OF(GENERAL_NAME) *alt;
692 debug(DBG_DBG, "subjectaltnameaddr");
694 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
698 ex = X509_get_ext(cert, loc);
699 alt = X509V3_EXT_d2i(ex);
703 n = sk_GENERAL_NAME_num(alt);
704 for (i = 0; i < n; i++) {
705 gn = sk_GENERAL_NAME_value(alt, i);
706 if (gn->type != GEN_IPADD)
709 v = (char *)ASN1_STRING_data(gn->d.ia5);
710 l = ASN1_STRING_length(gn->d.ia5);
711 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
712 && !memcmp(v, &addr, l)) {
717 GENERAL_NAMES_free(alt);
721 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
728 nm = X509_get_subject_name(cert);
731 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
734 e = X509_NAME_get_entry(nm, loc);
735 t = X509_NAME_ENTRY_get_data(e);
736 v = (char *) ASN1_STRING_data(t);
737 l = ASN1_STRING_length(t);
741 if (l == strlen(exact) && !strncasecmp(exact, v, l))
744 s = stringcopy((char *)v, l);
746 debug(DBG_ERR, "malloc failed");
749 if (regexec(regex, s, 0, NULL, 0)) {
760 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
761 int loc, i, l, n, r = 0;
764 STACK_OF(GENERAL_NAME) *alt;
767 debug(DBG_DBG, "subjectaltnameregexp");
769 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
773 ex = X509_get_ext(cert, loc);
774 alt = X509V3_EXT_d2i(ex);
778 n = sk_GENERAL_NAME_num(alt);
779 for (i = 0; i < n; i++) {
780 gn = sk_GENERAL_NAME_value(alt, i);
781 if (gn->type != type)
784 v = (char *)ASN1_STRING_data(gn->d.ia5);
785 l = ASN1_STRING_length(gn->d.ia5);
789 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
792 if (memcmp(v, exact, l))
795 s = stringcopy((char *)v, l);
797 debug(DBG_ERR, "malloc failed");
800 if (regexec(regex, s, 0, NULL, 0)) {
809 GENERAL_NAMES_free(alt);
813 X509 *verifytlscert(SSL *ssl) {
817 if (SSL_get_verify_result(ssl) != X509_V_OK) {
818 debug(DBG_ERR, "verifytlscert: basic validation failed");
819 while ((error = ERR_get_error()))
820 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
824 cert = SSL_get_peer_certificate(ssl);
826 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
830 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
832 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
833 struct in6_addr addr;
835 if (conf->certnamecheck && conf->prefixlen == 255) {
836 if (inet_pton(AF_INET, conf->host, &addr))
838 else if (inet_pton(AF_INET6, conf->host, &addr))
841 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
844 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
847 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
849 if (!cnregexp(cert, conf->host, NULL)) {
850 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
853 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
856 if (conf->certcnregex) {
857 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
858 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
861 debug(DBG_DBG, "verifyconfcert: CN matching regex");
863 if (conf->certuriregex) {
864 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
865 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
868 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
873 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
875 if (ATTRTYPE(attrs) == type)
877 length -= ATTRLEN(attrs);
878 attrs += ATTRLEN(attrs);
883 void freerq(struct request *rq) {
886 debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
889 if (rq->origusername)
890 free(rq->origusername);
896 radmsg_free(rq->msg);
900 void freerqoutdata(struct rqout *rqout) {
908 memset(&rqout->expiry, 0, sizeof(struct timeval));
911 void sendrq(struct request *rq) {
913 struct server *to = rq->to;
915 start = to->conf->statusserver ? 1 : 0;
916 pthread_mutex_lock(&to->newrq_mutex);
917 if (start && rq->msg->code == RAD_Status_Server) {
918 pthread_mutex_lock(to->requests[0].lock);
919 if (to->requests[0].rq) {
920 pthread_mutex_unlock(to->requests[0].lock);
921 debug(DBG_WARN, "sendrq: status server already in queue, dropping request");
928 /* might simplify if only try nextid, might be ok */
929 for (i = to->nextid; i < MAX_REQUESTS; i++) {
930 if (!to->requests[i].rq) {
931 pthread_mutex_lock(to->requests[i].lock);
932 if (!to->requests[i].rq)
934 pthread_mutex_unlock(to->requests[i].lock);
937 if (i == MAX_REQUESTS) {
938 for (i = start; i < to->nextid; i++) {
939 if (!to->requests[i].rq) {
940 pthread_mutex_lock(to->requests[i].lock);
941 if (!to->requests[i].rq)
943 pthread_mutex_unlock(to->requests[i].lock);
946 if (i == to->nextid) {
947 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
952 rq->newid = (uint8_t)i;
953 rq->msg->id = (uint8_t)i;
954 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
956 pthread_mutex_unlock(to->requests[i].lock);
957 debug(DBG_ERR, "sendrq: radmsg2buf failed");
961 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
962 to->requests[i].rq = rq;
963 pthread_mutex_unlock(to->requests[i].lock);
964 if (i >= start) /* i is not reserved for statusserver */
969 debug(DBG_DBG, "sendrq: signalling client writer");
970 pthread_cond_signal(&to->newrq_cond);
973 pthread_mutex_unlock(&to->newrq_mutex);
978 rmclientrq(rq, rq->msg->id);
980 pthread_mutex_unlock(&to->newrq_mutex);
983 void sendreply(struct request *rq) {
985 struct client *to = rq->from;
988 rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
989 radmsg_free(rq->msg);
993 debug(DBG_ERR, "sendreply: radmsg2buf failed");
997 pthread_mutex_lock(&to->replyq->mutex);
998 first = list_first(to->replyq->entries) == NULL;
1000 if (!list_push(to->replyq->entries, rq)) {
1001 pthread_mutex_unlock(&to->replyq->mutex);
1003 debug(DBG_ERR, "sendreply: malloc failed");
1008 debug(DBG_DBG, "signalling server writer");
1009 pthread_cond_signal(&to->replyq->cond);
1011 pthread_mutex_unlock(&to->replyq->mutex);
1014 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1015 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1016 static unsigned char first = 1;
1017 static EVP_MD_CTX mdctx;
1018 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1019 unsigned int md_len;
1020 uint8_t i, offset = 0, out[128];
1022 pthread_mutex_lock(&lock);
1024 EVP_MD_CTX_init(&mdctx);
1030 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1031 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1032 !EVP_DigestUpdate(&mdctx, input, 16) ||
1033 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1035 pthread_mutex_unlock(&lock);
1038 for (i = 0; i < 16; i++)
1039 out[offset + i] = hash[i] ^ in[offset + i];
1040 input = out + offset - 16;
1045 memcpy(in, out, len);
1046 pthread_mutex_unlock(&lock);
1050 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1051 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1052 static unsigned char first = 1;
1053 static EVP_MD_CTX mdctx;
1054 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1055 unsigned int md_len;
1056 uint8_t i, offset = 0, out[128];
1058 pthread_mutex_lock(&lock);
1060 EVP_MD_CTX_init(&mdctx);
1066 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1067 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1068 !EVP_DigestUpdate(&mdctx, input, 16) ||
1069 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1071 pthread_mutex_unlock(&lock);
1074 for (i = 0; i < 16; i++)
1075 out[offset + i] = hash[i] ^ in[offset + i];
1076 input = in + offset;
1081 memcpy(in, out, len);
1082 pthread_mutex_unlock(&lock);
1086 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1087 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1088 static unsigned char first = 1;
1089 static EVP_MD_CTX mdctx;
1090 unsigned char hash[EVP_MAX_MD_SIZE];
1091 unsigned int md_len;
1094 pthread_mutex_lock(&lock);
1096 EVP_MD_CTX_init(&mdctx);
1101 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1102 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1103 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1106 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1107 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1108 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1109 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1110 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1111 pthread_mutex_unlock(&lock);
1116 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1119 for (i = 0; i < 16; i++)
1122 for (offset = 16; offset < len; offset += 16) {
1124 printf("text + offset - 16 c(%d): ", offset / 16);
1125 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1127 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1128 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1129 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1130 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1132 pthread_mutex_unlock(&lock);
1136 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1139 for (i = 0; i < 16; i++)
1140 text[offset + i] ^= hash[i];
1144 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1147 pthread_mutex_unlock(&lock);
1151 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1152 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1153 static unsigned char first = 1;
1154 static EVP_MD_CTX mdctx;
1155 unsigned char hash[EVP_MAX_MD_SIZE];
1156 unsigned int md_len;
1160 pthread_mutex_lock(&lock);
1162 EVP_MD_CTX_init(&mdctx);
1167 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1168 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1169 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1172 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1173 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1174 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1175 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1176 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1177 pthread_mutex_unlock(&lock);
1182 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1185 for (i = 0; i < 16; i++)
1186 plain[i] = text[i] ^ hash[i];
1188 for (offset = 16; offset < len; offset += 16) {
1190 printf("text + offset - 16 c(%d): ", offset / 16);
1191 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1193 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1194 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1195 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1196 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1198 pthread_mutex_unlock(&lock);
1202 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1205 for (i = 0; i < 16; i++)
1206 plain[offset + i] = text[offset + i] ^ hash[i];
1209 memcpy(text, plain, len);
1211 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1214 pthread_mutex_unlock(&lock);
1218 struct realm *id2realm(struct list *realmlist, char *id) {
1219 struct list_node *entry;
1220 struct realm *realm, *subrealm = NULL;
1222 /* need to do locking for subrealms and check subrealm timers */
1223 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1224 realm = (struct realm *)entry->data;
1225 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1226 pthread_mutex_lock(&realm->subrealms_mutex);
1227 if (realm->subrealms)
1228 subrealm = id2realm(realm->subrealms, id);
1229 pthread_mutex_unlock(&realm->subrealms_mutex);
1230 return subrealm ? subrealm : realm;
1236 /* helper function, only used by removeserversubrealms() */
1237 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1238 struct list_node *entry;
1239 struct realm *realm;
1241 for (entry = list_first(realmlist); entry;) {
1242 realm = (struct realm *)entry->data;
1243 entry = list_next(entry);
1244 if (realm->srvconfs) {
1245 list_removedata(realm->srvconfs, srv);
1246 if (!list_first(realm->srvconfs)) {
1247 list_destroy(realm->srvconfs);
1248 realm->srvconfs = NULL;
1251 if (realm->accsrvconfs) {
1252 list_removedata(realm->accsrvconfs, srv);
1253 if (!list_first(realm->accsrvconfs)) {
1254 list_destroy(realm->accsrvconfs);
1255 realm->accsrvconfs = NULL;
1259 /* remove subrealm if no servers */
1260 if (!realm->srvconfs && !realm->accsrvconfs) {
1261 list_removedata(realmlist, realm);
1267 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1268 struct list_node *entry;
1269 struct realm *realm;
1271 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1272 realm = (struct realm *)entry->data;
1273 pthread_mutex_lock(&realm->subrealms_mutex);
1274 if (realm->subrealms) {
1275 _internal_removeserversubrealms(realm->subrealms, srv);
1276 if (!list_first(realm->subrealms)) {
1277 list_destroy(realm->subrealms);
1278 realm->subrealms = NULL;
1281 pthread_mutex_unlock(&realm->subrealms_mutex);
1285 int attrvalidate(unsigned char *attrs, int length) {
1286 while (length > 1) {
1287 if (ATTRLEN(attrs) < 2) {
1288 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1291 length -= ATTRLEN(attrs);
1293 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1296 attrs += ATTRLEN(attrs);
1299 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1303 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1304 if (len < 16 || len > 128 || len % 16) {
1305 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1309 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1310 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1314 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1316 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1317 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1323 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1326 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1327 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1330 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
1331 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1337 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1338 char *oldsecret, char *newsecret) {
1339 unsigned char *attr;
1341 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1342 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1343 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
1349 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1353 for (; attrs[0]; attrs += 2)
1354 if (attrs[0] == vendor && attrs[1] == subattr)
1359 /* returns 1 if entire element is to be removed, else 0 */
1360 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
1361 uint8_t alen, sublen;
1365 if (!removevendorattrs)
1368 memcpy(&vendor, attr->v, 4);
1369 vendor = ntohl(vendor);
1370 while (*removevendorattrs && *removevendorattrs != vendor)
1371 removevendorattrs += 2;
1372 if (!*removevendorattrs)
1375 if (findvendorsubattr(removevendorattrs, vendor, -1))
1376 return 1; /* remove entire vendor attribute */
1378 sublen = attr->l - 4;
1379 subattrs = attr->v + 4;
1381 if (!attrvalidate(subattrs, sublen)) {
1382 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1386 while (sublen > 1) {
1387 alen = ATTRLEN(subattrs);
1389 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1390 memmove(subattrs, subattrs + alen, sublen);
1398 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
1399 struct list_node *n, *p;
1403 n = list_first(msg->attrs);
1405 attr = (struct tlv *)n->data;
1406 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
1407 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
1408 list_removedata(msg->attrs, attr);
1410 n = p ? list_next(p) : list_first(msg->attrs);
1417 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
1418 struct list_node *n;
1421 for (n = list_first(addattrs); n; n = list_next(n)) {
1422 a = copytlv((struct tlv *)n->data);
1425 if (!radmsg_add(msg, a)) {
1433 int resizeattr(struct tlv *attr, uint8_t newlen) {
1436 if (newlen != attr->l) {
1437 newv = realloc(attr->v, newlen);
1446 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1447 size_t nmatch = 10, reslen = 0, start = 0;
1448 regmatch_t pmatch[10], *pfield;
1452 in = stringcopy((char *)attr->v, attr->l);
1456 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1461 out = modattr->replacement;
1463 for (i = start; out[i]; i++) {
1464 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1465 pfield = &pmatch[out[i + 1] - '0'];
1466 if (pfield->rm_so >= 0) {
1467 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1473 reslen += i - start;
1475 debug(DBG_WARN, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1480 if (!resizeattr(attr, reslen)) {
1487 for (i = start; out[i]; i++) {
1488 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1489 pfield = &pmatch[out[i + 1] - '0'];
1490 if (pfield->rm_so >= 0) {
1491 memcpy(attr->v + reslen, out + start, i - start);
1492 reslen += i - start;
1493 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1494 reslen += pfield->rm_eo - pfield->rm_so;
1501 memcpy(attr->v + reslen, out + start, i - start);
1505 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1506 struct list_node *n, *m;
1508 for (n = list_first(msg->attrs); n; n = list_next(n))
1509 for (m = list_first(modattrs); m; m = list_next(m))
1510 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1511 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1516 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1519 if (rewrite->removeattrs || rewrite->removevendorattrs)
1520 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1521 if (rewrite->addattrs && !dorewriteadd(msg, rewrite->addattrs))
1523 if (rewrite->modattrs && !dorewritemod(msg, rewrite->modattrs))
1528 int rewriteusername(struct request *rq, struct tlv *attr) {
1529 char *orig = (char *)tlv2str(attr);
1530 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1534 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1535 rq->origusername = (char *)orig;
1541 const char *radmsgtype2string(uint8_t code) {
1542 static const char *rad_msg_names[] = {
1543 "", "Access-Request", "Access-Accept", "Access-Reject",
1544 "Accounting-Request", "Accounting-Response", "", "",
1545 "", "", "", "Access-Challenge",
1546 "Status-Server", "Status-Client"
1548 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1551 void char2hex(char *h, unsigned char c) {
1552 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1553 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1554 h[0] = hexdigits[c / 16];
1555 h[1] = hexdigits[c % 16];
1559 uint8_t *radattr2ascii(struct tlv *attr) {
1567 for (i = 0; i < attr->l; i++)
1568 if (attr->v[i] < 32 || attr->v[i] > 126)
1571 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1578 for (i = 0; i < attr->l; i++)
1579 if (attr->v[i] < 32 || attr->v[i] > 126) {
1581 char2hex((char *)d, attr->v[i]);
1589 void acclog(struct radmsg *msg, char *host) {
1593 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1595 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1598 username = radattr2ascii(attr);
1600 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1605 void respond(struct request *rq, uint8_t code, char *message) {
1609 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1611 debug(DBG_ERR, "respond: malloc failed");
1614 if (message && *message) {
1615 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1616 if (!attr || !radmsg_add(msg, attr)) {
1619 debug(DBG_ERR, "respond: malloc failed");
1624 radmsg_free(rq->msg);
1626 debug(DBG_DBG, "respond: sending %s to %s", radmsgtype2string(msg->code), rq->from->conf->host);
1631 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1632 struct list_node *entry;
1633 struct clsrvconf *server, *best = NULL, *first = NULL;
1635 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1636 server = (struct clsrvconf *)entry->data;
1637 if (!server->servers)
1641 if (!server->servers->connectionok)
1643 if (!server->servers->lostrqs)
1649 if (server->servers->lostrqs < best->servers->lostrqs)
1652 return best ? best : first;
1655 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1656 struct clsrvconf *srvconf;
1657 char *id = (char *)tlv2str(username);
1661 *realm = id2realm(realms, id);
1666 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1667 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1672 if (!acc && !srvconf->servers)
1673 adddynamicrealmserver(*realm, srvconf, id);
1675 return srvconf->servers;
1679 struct request *newrequest() {
1682 rq = malloc(sizeof(struct request));
1684 debug(DBG_ERR, "newrequest: malloc failed");
1687 memset(rq, 0, sizeof(struct request));
1689 gettimeofday(&rq->created, NULL);
1693 int addclientrq(struct request *rq) {
1697 r = rq->from->rqs[rq->rqid];
1699 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1700 gettimeofday(&now, NULL);
1701 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1703 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1707 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1714 rq->from->rqs[rq->rqid] = rq;
1718 void rmclientrq(struct request *rq, uint8_t id) {
1721 r = rq->from->rqs[id];
1724 rq->from->rqs[id] = NULL;
1728 /* returns 0 if validation/authentication fails, else 1 */
1729 int radsrv(struct request *rq) {
1730 struct radmsg *msg = NULL;
1732 uint8_t *userascii = NULL;
1733 struct realm *realm = NULL;
1734 struct server *to = NULL;
1735 struct client *from = rq->from;
1737 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1742 debug(DBG_WARN, "radsrv: message validation failed, ignoring packet");
1749 memcpy(rq->rqauth, msg->auth, 16);
1751 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1752 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1753 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1757 if (!addclientrq(rq))
1760 if (msg->code == RAD_Status_Server) {
1761 respond(rq, RAD_Access_Accept, NULL);
1765 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1767 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1770 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1772 if (msg->code == RAD_Accounting_Request) {
1773 acclog(msg, from->conf->host);
1774 respond(rq, RAD_Accounting_Response, NULL);
1776 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1780 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1781 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1785 userascii = radattr2ascii(attr);
1788 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1790 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1792 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1797 if (realm->message && msg->code == RAD_Access_Request) {
1798 debug(DBG_INFO, "radsrv: sending reject to %s for %s", from->conf->host, userascii);
1799 respond(rq, RAD_Access_Reject, realm->message);
1800 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1801 acclog(msg, from->conf->host);
1802 respond(rq, RAD_Accounting_Response, NULL);
1807 if (options.loopprevention && !strcmp(from->conf->name, to->conf->name)) {
1808 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
1809 from->conf->name, to->conf->name);
1813 if (msg->code == RAD_Accounting_Request)
1814 memset(msg->auth, 0, 16);
1815 else if (!RAND_bytes(msg->auth, 16)) {
1816 debug(DBG_WARN, "radsrv: failed to generate random auth");
1821 printfchars(NULL, "auth", "%02x ", auth, 16);
1824 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1826 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1827 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1831 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1833 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1834 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1838 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1847 rmclientrq(rq, msg->id);
1854 void replyh(struct server *server, unsigned char *buf) {
1855 struct client *from;
1856 struct rqout *rqout;
1858 unsigned char *subattrs;
1859 uint8_t *username, *stationid, *replymsg;
1860 struct radmsg *msg = NULL;
1862 struct list_node *node;
1864 server->connectionok = 1;
1865 server->lostrqs = 0;
1867 rqout = server->requests + buf[1];
1868 pthread_mutex_lock(rqout->lock);
1869 if (!rqout->tries) {
1872 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1876 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1880 debug(DBG_WARN, "replyh: message validation failed, ignoring packet");
1883 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1884 && msg->code != RAD_Accounting_Response) {
1885 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1888 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1890 gettimeofday(&server->lastrcv, NULL);
1892 if (rqout->rq->msg->code == RAD_Status_Server) {
1893 freerqoutdata(rqout);
1894 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
1898 gettimeofday(&server->lastreply, NULL);
1899 from = rqout->rq->from;
1901 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1902 debug(DBG_WARN, "replyh: rewritein failed");
1907 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1908 attr = (struct tlv *)node->data;
1909 if (attr->t != RAD_Attr_Vendor_Specific)
1913 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
1916 sublen = attr->l - 4;
1917 subattrs = attr->v + 4;
1918 if (!attrvalidate(subattrs, sublen) ||
1919 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1920 rqout->rq, server->conf->secret, from->conf->secret) ||
1921 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1922 rqout->rq, server->conf->secret, from->conf->secret))
1926 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1930 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1931 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
1933 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
1934 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
1937 debug(DBG_INFO, "%s for user %s stationid %s from %s (%s)",
1938 radmsgtype2string(msg->code), username, stationid, server->conf->host, replymsg);
1941 debug(DBG_INFO, "%s for user %s stationid %s from %s",
1942 radmsgtype2string(msg->code), username, stationid, server->conf->host);
1946 debug(DBG_INFO, "%s for user %s from %s (%s)",
1947 radmsgtype2string(msg->code), username, server->conf->host, replymsg);
1950 debug(DBG_INFO, "%s for user %s from %s",
1951 radmsgtype2string(msg->code), username, server->conf->host);
1957 msg->id = (char)rqout->rq->rqid;
1958 memcpy(msg->auth, rqout->rq->rqauth, 16);
1961 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1964 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
1965 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
1966 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1969 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
1972 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
1973 debug(DBG_WARN, "replyh: rewriteout failed");
1977 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
1978 radmsg_free(rqout->rq->msg);
1979 rqout->rq->msg = msg;
1980 rqout->rq->refcount++;
1981 sendreply(rqout->rq);
1982 freerqoutdata(rqout);
1983 pthread_mutex_unlock(rqout->lock);
1988 pthread_mutex_unlock(rqout->lock);
1992 struct request *createstatsrvrq() {
1999 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
2002 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
2005 if (!radmsg_add(rq->msg, attr)) {
2016 /* code for removing state not finished */
2017 void *clientwr(void *arg) {
2018 struct server *server = (struct server *)arg;
2019 struct rqout *rqout = NULL;
2020 pthread_t clientrdth;
2021 int i, dynconffail = 0;
2024 struct timeval now, laststatsrv;
2025 struct timespec timeout;
2026 struct request *statsrvrq;
2027 struct clsrvconf *conf;
2029 conf = server->conf;
2031 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2036 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2037 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2041 memset(&timeout, 0, sizeof(struct timespec));
2043 if (conf->statusserver) {
2044 gettimeofday(&server->lastrcv, NULL);
2045 gettimeofday(&laststatsrv, NULL);
2048 if (conf->pdef->connecter) {
2049 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2051 server->connectionok = 1;
2052 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
2053 debug(DBG_ERR, "clientwr: pthread_create failed");
2057 server->connectionok = 1;
2060 pthread_mutex_lock(&server->newrq_mutex);
2061 if (!server->newrq) {
2062 gettimeofday(&now, NULL);
2063 /* random 0-7 seconds */
2064 RAND_bytes(&rnd, 1);
2066 if (conf->statusserver) {
2067 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2068 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
2070 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
2071 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
2073 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2074 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2077 if (timeout.tv_sec > now.tv_sec)
2078 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2080 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2083 if (server->newrq) {
2084 debug(DBG_DBG, "clientwr: got new request");
2089 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2091 pthread_mutex_unlock(&server->newrq_mutex);
2093 for (i = 0; i < MAX_REQUESTS; i++) {
2094 if (server->clientrdgone) {
2095 pthread_join(clientrdth, NULL);
2099 for (; i < MAX_REQUESTS; i++) {
2100 rqout = server->requests + i;
2102 pthread_mutex_lock(rqout->lock);
2105 pthread_mutex_unlock(rqout->lock);
2109 if (i == MAX_REQUESTS)
2112 gettimeofday(&now, NULL);
2113 if (now.tv_sec < rqout->expiry.tv_sec) {
2114 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2115 timeout.tv_sec = rqout->expiry.tv_sec;
2116 pthread_mutex_unlock(rqout->lock);
2120 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2121 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2122 if (conf->statusserver) {
2123 if (*rqout->rq->buf == RAD_Status_Server) {
2124 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2125 if (server->lostrqs < 255)
2129 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2130 if (server->lostrqs < 255)
2133 freerqoutdata(rqout);
2134 pthread_mutex_unlock(rqout->lock);
2138 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2139 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2140 timeout.tv_sec = rqout->expiry.tv_sec;
2142 conf->pdef->clientradput(server, rqout->rq->buf);
2143 pthread_mutex_unlock(rqout->lock);
2145 if (conf->statusserver && server->connectionok) {
2146 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2147 gettimeofday(&now, NULL);
2148 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
2150 statsrvrq = createstatsrvrq();
2152 statsrvrq->to = server;
2153 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2160 conf->servers = NULL;
2161 if (server->dynamiclookuparg) {
2162 removeserversubrealms(realms, conf);
2166 freeclsrvconf(conf);
2168 freeserver(server, 1);
2169 ERR_remove_state(0);
2173 void createlistener(uint8_t type, char *arg) {
2175 struct clsrvconf *listenres;
2176 struct addrinfo *res;
2177 int s = -1, on = 1, *sp = NULL;
2179 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2181 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2183 for (res = listenres->addrinfo; res; res = res->ai_next) {
2184 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2186 debug(DBG_WARN, "createlistener: socket failed");
2189 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2191 if (res->ai_family == AF_INET6)
2192 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2194 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2195 debug(DBG_WARN, "createlistener: bind failed");
2201 sp = malloc(sizeof(int));
2203 debugx(1, DBG_ERR, "malloc failed");
2205 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
2206 debugx(1, DBG_ERR, "pthread_create failed");
2210 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2212 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
2213 listenres->host ? listenres->host : "*", listenres->port);
2214 freeclsrvres(listenres);
2217 void createlisteners(uint8_t type, char **args) {
2221 for (i = 0; args[i]; i++)
2222 createlistener(type, args[i]);
2224 createlistener(type, NULL);
2228 void ssl_info_callback(const SSL *ssl, int where, int ret) {
2232 w = where & ~SSL_ST_MASK;
2234 if (w & SSL_ST_CONNECT)
2236 else if (w & SSL_ST_ACCEPT)
2241 if (where & SSL_CB_LOOP)
2242 debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
2243 else if (where & SSL_CB_ALERT) {
2244 s = (where & SSL_CB_READ) ? "read" : "write";
2245 debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
2247 else if (where & SSL_CB_EXIT) {
2249 debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
2251 debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
2256 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2257 SSL_CTX *ctx = NULL;
2258 STACK_OF(X509_NAME) *calist;
2261 unsigned long error;
2264 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2265 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2266 for (i = 0; i < CRYPTO_num_locks(); i++) {
2267 ssl_lock_count[i] = 0;
2268 pthread_mutex_init(&ssl_locks[i], NULL);
2270 CRYPTO_set_id_callback(ssl_thread_id);
2271 CRYPTO_set_locking_callback(ssl_locking_callback);
2273 SSL_load_error_strings();
2276 while (!RAND_status()) {
2277 time_t t = time(NULL);
2278 pid_t pid = getpid();
2279 RAND_seed((unsigned char *)&t, sizeof(time_t));
2280 RAND_seed((unsigned char *)&pid, sizeof(pid));
2286 ctx = SSL_CTX_new(TLSv1_method());
2288 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2292 ctx = SSL_CTX_new(DTLSv1_method());
2294 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2296 SSL_CTX_set_read_ahead(ctx, 1);
2300 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2304 if (conf->certkeypwd) {
2305 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2306 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2308 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2309 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2310 !SSL_CTX_check_private_key(ctx) ||
2311 !SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2312 while ((error = ERR_get_error()))
2313 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2314 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2319 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2320 if (!conf->cacertfile || calist) {
2321 if (conf->cacertpath) {
2323 calist = sk_X509_NAME_new_null();
2324 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2325 sk_X509_NAME_free(calist);
2331 while ((error = ERR_get_error()))
2332 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2333 debug(DBG_ERR, "tlscreatectx: Error adding CA subjects in TLS context %s", conf->name);
2337 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2338 SSL_CTX_set_client_CA_list(ctx, calist);
2340 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2341 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2343 if (conf->crlcheck) {
2344 x509_s = SSL_CTX_get_cert_store(ctx);
2345 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2348 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
2352 struct tls *tlsgettls(char *alt1, char *alt2) {
2355 t = hash_read(tlsconfs, alt1, strlen(alt1));
2357 t = hash_read(tlsconfs, alt2, strlen(alt2));
2361 SSL_CTX *tlsgetctx(uint8_t type, struct tls *t) {
2366 gettimeofday(&now, NULL);
2370 if (t->tlsexpiry && t->tlsctx) {
2371 if (t->tlsexpiry < now.tv_sec) {
2372 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
2373 SSL_CTX_free(t->tlsctx);
2374 return t->tlsctx = tlscreatectx(RAD_TLS, t);
2378 t->tlsctx = tlscreatectx(RAD_TLS, t);
2380 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
2384 if (t->dtlsexpiry && t->dtlsctx) {
2385 if (t->dtlsexpiry < now.tv_sec) {
2386 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
2387 SSL_CTX_free(t->dtlsctx);
2388 return t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2392 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2394 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
2401 struct list *addsrvconfs(char *value, char **names) {
2402 struct list *conflist;
2404 struct list_node *entry;
2405 struct clsrvconf *conf = NULL;
2407 if (!names || !*names)
2410 conflist = list_create();
2412 debug(DBG_ERR, "malloc failed");
2416 for (n = 0; names[n]; n++) {
2417 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2418 conf = (struct clsrvconf *)entry->data;
2419 if (!strcasecmp(names[n], conf->name))
2423 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2424 list_destroy(conflist);
2427 if (!list_push(conflist, conf)) {
2428 debug(DBG_ERR, "malloc failed");
2429 list_destroy(conflist);
2432 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2437 void freerealm(struct realm *realm) {
2441 free(realm->message);
2442 regfree(&realm->regex);
2443 pthread_mutex_destroy(&realm->subrealms_mutex);
2444 if (realm->subrealms)
2445 list_destroy(realm->subrealms);
2446 if (realm->srvconfs) {
2447 /* emptying list without freeing data */
2448 while (list_shift(realm->srvconfs));
2449 list_destroy(realm->srvconfs);
2451 if (realm->accsrvconfs) {
2452 /* emptying list without freeing data */
2453 while (list_shift(realm->accsrvconfs));
2454 list_destroy(realm->accsrvconfs);
2459 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2461 struct realm *realm;
2462 char *s, *regex = NULL;
2464 if (*value == '/') {
2465 /* regexp, remove optional trailing / if present */
2466 if (value[strlen(value) - 1] == '/')
2467 value[strlen(value) - 1] = '\0';
2469 /* not a regexp, let us make it one */
2470 if (*value == '*' && !value[1])
2471 regex = stringcopy(".*", 0);
2473 for (n = 0, s = value; *s;)
2476 regex = malloc(strlen(value) + n + 3);
2479 for (n = 1, s = value; *s; s++) {
2489 debug(DBG_ERR, "malloc failed");
2493 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2496 realm = malloc(sizeof(struct realm));
2498 debug(DBG_ERR, "malloc failed");
2501 memset(realm, 0, sizeof(struct realm));
2503 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
2504 debug(DBG_ERR, "mutex init failed");
2510 realm->name = stringcopy(value, 0);
2512 debug(DBG_ERR, "malloc failed");
2515 if (message && strlen(message) > 253) {
2516 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2519 realm->message = message;
2520 realm->accresp = accresp;
2522 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2523 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2527 if (servers && *servers) {
2528 realm->srvconfs = addsrvconfs(value, servers);
2529 if (!realm->srvconfs)
2533 if (accservers && *accservers) {
2534 realm->accsrvconfs = addsrvconfs(value, accservers);
2535 if (!realm->accsrvconfs)
2539 if (!list_push(realmlist, realm)) {
2540 debug(DBG_ERR, "malloc failed");
2541 pthread_mutex_destroy(&realm->subrealms_mutex);
2545 debug(DBG_DBG, "addrealm: added realm %s", value);
2555 for (n = 0; servers[n]; n++)
2560 for (n = 0; accservers[n]; n++)
2561 free(accservers[n]);
2567 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2568 struct clsrvconf *srvconf;
2569 struct realm *newrealm = NULL;
2570 char *realmname, *s;
2573 if (!conf->dynamiclookupcommand)
2576 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2577 realmname = strrchr(id, '@');
2583 for (s = realmname; *s; s++)
2584 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2587 pthread_mutex_lock(&realm->subrealms_mutex);
2588 /* exit if we now already got a matching subrealm */
2589 if (id2realm(realm->subrealms, id))
2591 srvconf = malloc(sizeof(struct clsrvconf));
2593 debug(DBG_ERR, "malloc failed");
2597 if (!addserver(srvconf))
2600 if (!realm->subrealms)
2601 realm->subrealms = list_create();
2602 if (!realm->subrealms)
2604 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2608 /* add server and accserver to newrealm */
2609 newrealm->srvconfs = list_create();
2610 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2611 debug(DBG_ERR, "malloc failed");
2614 newrealm->accsrvconfs = list_create();
2615 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2616 debug(DBG_ERR, "malloc failed");
2620 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2622 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2623 debug(DBG_ERR, "pthread_create failed");
2626 pthread_detach(clientth);
2631 list_removedata(realm->subrealms, newrealm);
2632 freerealm(newrealm);
2633 if (!list_first(realm->subrealms)) {
2634 list_destroy(realm->subrealms);
2635 realm->subrealms = NULL;
2638 freeserver(srvconf->servers, 1);
2640 debug(DBG_ERR, "failed to create dynamic server");
2643 pthread_mutex_unlock(&realm->subrealms_mutex);
2646 int dynamicconfig(struct server *server) {
2647 int ok, fd[2], status;
2649 struct clsrvconf *conf = server->conf;
2650 struct gconffile *cf = NULL;
2652 /* for now we only learn hostname/address */
2653 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2656 debug(DBG_ERR, "dynamicconfig: pipe error");
2661 debug(DBG_ERR, "dynamicconfig: fork error");
2665 } else if (pid == 0) {
2668 if (fd[1] != STDOUT_FILENO) {
2669 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2670 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2673 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2674 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2678 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2679 ok = getgenericconfig(&cf, NULL,
2680 "Server", CONF_CBK, confserver_cb, (void *)conf,
2685 if (waitpid(pid, &status, 0) < 0) {
2686 debug(DBG_ERR, "dynamicconfig: wait error");
2691 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2699 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2703 int addmatchcertattr(struct clsrvconf *conf) {
2707 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2708 r = &conf->certcnregex;
2709 v = conf->matchcertattr + 4;
2710 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2711 r = &conf->certuriregex;
2712 v = conf->matchcertattr + 20;
2717 /* regexp, remove optional trailing / if present */
2718 if (v[strlen(v) - 1] == '/')
2719 v[strlen(v) - 1] = '\0';
2723 *r = malloc(sizeof(regex_t));
2725 debug(DBG_ERR, "malloc failed");
2728 if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2731 debug(DBG_ERR, "failed to compile regular expression %s", v);
2737 /* should accept both names and numeric values, only numeric right now */
2738 uint8_t attrname2val(char *attrname) {
2741 val = atoi(attrname);
2742 return val > 0 && val < 256 ? val : 0;
2745 /* should accept both names and numeric values, only numeric right now */
2746 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2749 *vendor = atoi(attrname);
2750 s = strchr(attrname, ':');
2755 *type = atoi(s + 1);
2756 return *type >= 0 && *type < 256;
2759 /* should accept both names and numeric values, only numeric right now */
2760 struct tlv *extractattr(char *nameval) {
2765 s = strchr(nameval, ':');
2766 name = atoi(nameval);
2767 if (!s || name < 1 || name > 255)
2769 len = strlen(s + 1);
2772 a = malloc(sizeof(struct tlv));
2775 a->v = (uint8_t *)stringcopy(s + 1, 0);
2785 /* should accept both names and numeric values, only numeric right now */
2786 struct modattr *extractmodattr(char *nameval) {
2791 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2795 s = strchr(nameval, ':');
2796 name = atoi(nameval);
2797 if (!s || name < 1 || name > 255 || s[1] != '/')
2801 /* regexp, remove optional trailing / if present */
2802 if (s[strlen(s) - 1] == '/')
2803 s[strlen(s) - 1] = '\0';
2811 m = malloc(sizeof(struct modattr));
2813 debug(DBG_ERR, "malloc failed");
2818 m->replacement = stringcopy(t, 0);
2819 if (!m->replacement) {
2821 debug(DBG_ERR, "malloc failed");
2825 m->regex = malloc(sizeof(regex_t));
2827 free(m->replacement);
2829 debug(DBG_ERR, "malloc failed");
2833 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2835 free(m->replacement);
2837 debug(DBG_ERR, "failed to compile regular expression %s", s);
2844 struct rewrite *getrewrite(char *alt1, char *alt2) {
2847 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2849 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2854 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
2855 struct rewrite *rewrite = NULL;
2857 uint8_t *rma = NULL;
2858 uint32_t *p, *rmva = NULL;
2859 struct list *adda = NULL, *moda = NULL;
2864 for (n = 0; rmattrs[n]; n++);
2865 rma = calloc(n + 1, sizeof(uint8_t));
2867 debugx(1, DBG_ERR, "malloc failed");
2869 for (i = 0; i < n; i++) {
2870 if (!(rma[i] = attrname2val(rmattrs[i])))
2871 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
2879 for (n = 0; rmvattrs[n]; n++);
2880 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2882 debugx(1, DBG_ERR, "malloc failed");
2884 for (p = rmva, i = 0; i < n; i++, p += 2) {
2885 if (!vattrname2val(rmvattrs[i], p, p + 1))
2886 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
2894 adda = list_create();
2896 debugx(1, DBG_ERR, "malloc failed");
2897 for (i = 0; addattrs[i]; i++) {
2898 a = extractattr(addattrs[i]);
2900 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
2902 if (!list_push(adda, a))
2903 debugx(1, DBG_ERR, "malloc failed");
2909 moda = list_create();
2911 debugx(1, DBG_ERR, "malloc failed");
2912 for (i = 0; modattrs[i]; i++) {
2913 m = extractmodattr(modattrs[i]);
2915 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
2917 if (!list_push(moda, m))
2918 debugx(1, DBG_ERR, "malloc failed");
2923 if (rma || rmva || adda || moda) {
2924 rewrite = malloc(sizeof(struct rewrite));
2926 debugx(1, DBG_ERR, "malloc failed");
2927 rewrite->removeattrs = rma;
2928 rewrite->removevendorattrs = rmva;
2929 rewrite->addattrs = adda;
2930 rewrite->modattrs = moda;
2933 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2934 debugx(1, DBG_ERR, "malloc failed");
2935 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2938 void freeclsrvconf(struct clsrvconf *conf) {
2944 free(conf->matchcertattr);
2945 if (conf->certcnregex)
2946 regfree(conf->certcnregex);
2947 if (conf->certuriregex)
2948 regfree(conf->certuriregex);
2949 free(conf->confrewritein);
2950 free(conf->confrewriteout);
2951 if (conf->rewriteusername) {
2952 if (conf->rewriteusername->regex)
2953 regfree(conf->rewriteusername->regex);
2954 free(conf->rewriteusername->replacement);
2955 free(conf->rewriteusername);
2957 free(conf->dynamiclookupcommand);
2958 free(conf->rewritein);
2959 free(conf->rewriteout);
2961 freeaddrinfo(conf->addrinfo);
2963 pthread_mutex_destroy(conf->lock);
2966 /* not touching ssl_ctx, clients and servers */
2970 int mergeconfstring(char **dst, char **src) {
2979 t = stringcopy(*dst, 0);
2981 debug(DBG_ERR, "malloc failed");
2989 /* assumes dst is a shallow copy */
2990 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2991 if (!mergeconfstring(&dst->name, &src->name) ||
2992 !mergeconfstring(&dst->host, &src->host) ||
2993 !mergeconfstring(&dst->port, &src->port) ||
2994 !mergeconfstring(&dst->secret, &src->secret) ||
2995 !mergeconfstring(&dst->tls, &src->tls) ||
2996 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2997 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2998 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2999 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3002 dst->pdef = src->pdef;
3003 dst->statusserver = src->statusserver;
3004 dst->certnamecheck = src->certnamecheck;
3005 if (src->retryinterval != 255)
3006 dst->retryinterval = src->retryinterval;
3007 if (src->retrycount != 255)
3008 dst->retrycount = src->retrycount;
3012 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3013 struct clsrvconf *conf;
3014 char *conftype = NULL, *rewriteinalias = NULL;
3015 long int dupinterval = LONG_MIN;
3017 debug(DBG_DBG, "confclient_cb called for %s", block);
3019 conf = malloc(sizeof(struct clsrvconf));
3021 debugx(1, DBG_ERR, "malloc failed");
3022 memset(conf, 0, sizeof(struct clsrvconf));
3023 conf->certnamecheck = 1;
3025 if (!getgenericconfig(cf, block,
3026 "type", CONF_STR, &conftype,
3027 "host", CONF_STR, &conf->host,
3028 "secret", CONF_STR, &conf->secret,
3029 "tls", CONF_STR, &conf->tls,
3030 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3031 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3032 "DuplicateInterval", CONF_LINT, &dupinterval,
3033 "rewrite", CONF_STR, &rewriteinalias,
3034 "rewriteIn", CONF_STR, &conf->confrewritein,
3035 "rewriteOut", CONF_STR, &conf->confrewriteout,
3036 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
3039 debugx(1, DBG_ERR, "configuration error");
3041 conf->name = stringcopy(val, 0);
3043 conf->host = stringcopy(val, 0);
3044 if (!conf->name || !conf->host)
3045 debugx(1, DBG_ERR, "malloc failed");
3048 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3049 conf->type = protoname2int(conftype);
3050 conf->pdef = &protodefs[conf->type];
3051 if (!conf->pdef->name)
3052 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3055 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3056 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
3058 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3059 if (conf->matchcertattr && !addmatchcertattr(conf))
3060 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3063 if (dupinterval != LONG_MIN) {
3064 if (dupinterval < 0 || dupinterval > 255)
3065 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
3066 conf->dupinterval = (uint8_t)dupinterval;
3068 conf->dupinterval = conf->pdef->duplicateintervaldefault;
3070 if (!conf->confrewritein)
3071 conf->confrewritein = rewriteinalias;
3073 free(rewriteinalias);
3074 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
3075 if (conf->confrewriteout)
3076 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3078 if (conf->confrewriteusername) {
3079 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
3080 if (!conf->rewriteusername)
3081 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3084 if (!resolvepeer(conf, 0))
3085 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3087 if (!conf->secret) {
3088 if (!conf->pdef->secretdefault)
3089 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3090 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3092 debugx(1, DBG_ERR, "malloc failed");
3095 conf->lock = malloc(sizeof(pthread_mutex_t));
3097 debugx(1, DBG_ERR, "malloc failed");
3099 pthread_mutex_init(conf->lock, NULL);
3100 if (!list_push(clconfs, conf))
3101 debugx(1, DBG_ERR, "malloc failed");
3105 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3106 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3107 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
3108 if (!conf->tlsconf) {
3109 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3112 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3113 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3119 conf->port = stringcopy(conf->pdef->portdefault, 0);
3121 debug(DBG_ERR, "malloc failed");
3126 if (conf->retryinterval == 255)
3127 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3128 if (conf->retrycount == 255)
3129 conf->retrycount = protodefs[conf->type].retrycountdefault;
3131 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
3132 if (conf->confrewriteout)
3133 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3135 if (!conf->secret) {
3136 if (!conf->pdef->secretdefault) {
3137 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3140 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3141 if (!conf->secret) {
3142 debug(DBG_ERR, "malloc failed");
3147 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3148 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3154 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3155 struct clsrvconf *conf, *resconf;
3156 char *conftype = NULL, *rewriteinalias = NULL;
3157 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3159 debug(DBG_DBG, "confserver_cb called for %s", block);
3161 conf = malloc(sizeof(struct clsrvconf));
3163 debug(DBG_ERR, "malloc failed");
3166 memset(conf, 0, sizeof(struct clsrvconf));
3167 resconf = (struct clsrvconf *)arg;
3169 conf->statusserver = resconf->statusserver;
3170 conf->certnamecheck = resconf->certnamecheck;
3172 conf->certnamecheck = 1;
3174 if (!getgenericconfig(cf, block,
3175 "type", CONF_STR, &conftype,
3176 "host", CONF_STR, &conf->host,
3177 "port", CONF_STR, &conf->port,
3178 "secret", CONF_STR, &conf->secret,
3179 "tls", CONF_STR, &conf->tls,
3180 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3181 "rewrite", CONF_STR, &rewriteinalias,
3182 "rewriteIn", CONF_STR, &conf->confrewritein,
3183 "rewriteOut", CONF_STR, &conf->confrewriteout,
3184 "StatusServer", CONF_BLN, &conf->statusserver,
3185 "RetryInterval", CONF_LINT, &retryinterval,
3186 "RetryCount", CONF_LINT, &retrycount,
3187 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3188 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3191 debug(DBG_ERR, "configuration error");
3195 conf->name = stringcopy(val, 0);
3197 debug(DBG_ERR, "malloc failed");
3201 conf->host = stringcopy(val, 0);
3203 debug(DBG_ERR, "malloc failed");
3209 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3210 conf->type = protoname2int(conftype);
3211 conf->pdef = &protodefs[conf->type];
3212 if (!conf->pdef->name) {
3213 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3219 if (!conf->confrewritein)
3220 conf->confrewritein = rewriteinalias;
3222 free(rewriteinalias);
3223 rewriteinalias = NULL;
3225 if (retryinterval != LONG_MIN) {
3226 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3227 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3230 conf->retryinterval = (uint8_t)retryinterval;
3232 conf->retryinterval = 255;
3234 if (retrycount != LONG_MIN) {
3235 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3236 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3239 conf->retrycount = (uint8_t)retrycount;
3241 conf->retrycount = 255;
3244 if (!mergesrvconf(resconf, conf))
3248 if (conf->dynamiclookupcommand) {
3249 free(conf->dynamiclookupcommand);
3250 conf->dynamiclookupcommand = NULL;
3254 if (resconf || !conf->dynamiclookupcommand) {
3255 if (!compileserverconfig(conf, block))
3262 if (!list_push(srvconfs, conf)) {
3263 debug(DBG_ERR, "malloc failed");
3270 free(rewriteinalias);
3271 freeclsrvconf(conf);
3275 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3276 char **servers = NULL, **accservers = NULL, *msg = NULL;
3277 uint8_t accresp = 0;
3279 debug(DBG_DBG, "confrealm_cb called for %s", block);
3281 if (!getgenericconfig(cf, block,
3282 "server", CONF_MSTR, &servers,
3283 "accountingServer", CONF_MSTR, &accservers,
3284 "ReplyMessage", CONF_STR, &msg,
3285 "AccountingResponse", CONF_BLN, &accresp,
3288 debugx(1, DBG_ERR, "configuration error");
3290 addrealm(realms, val, servers, accservers, msg, accresp);
3294 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3296 long int expiry = LONG_MIN;
3298 debug(DBG_DBG, "conftls_cb called for %s", block);
3300 conf = malloc(sizeof(struct tls));
3302 debug(DBG_ERR, "conftls_cb: malloc failed");
3305 memset(conf, 0, sizeof(struct tls));
3307 if (!getgenericconfig(cf, block,
3308 "CACertificateFile", CONF_STR, &conf->cacertfile,
3309 "CACertificatePath", CONF_STR, &conf->cacertpath,
3310 "CertificateFile", CONF_STR, &conf->certfile,
3311 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3312 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3313 "CacheExpiry", CONF_LINT, &expiry,
3314 "CRLCheck", CONF_BLN, &conf->crlcheck,
3317 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3320 if (!conf->certfile || !conf->certkeyfile) {
3321 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3324 if (!conf->cacertfile && !conf->cacertpath) {
3325 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3328 if (expiry != LONG_MIN) {
3330 debug(DBG_ERR, "error in block %s, value of option CacheExpiry is %ld, may not be negative", val, expiry);
3333 conf->cacheexpiry = expiry;
3336 conf->name = stringcopy(val, 0);
3338 debug(DBG_ERR, "conftls_cb: malloc failed");
3342 if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
3343 debug(DBG_ERR, "conftls_cb: malloc failed");
3347 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3351 free(conf->cacertfile);
3352 free(conf->cacertpath);
3353 free(conf->certfile);
3354 free(conf->certkeyfile);
3355 free(conf->certkeypwd);
3360 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3361 char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3363 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3365 if (!getgenericconfig(cf, block,
3366 "removeAttribute", CONF_MSTR, &rmattrs,
3367 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3368 "addAttribute", CONF_MSTR, &addattrs,
3369 "modifyAttribute", CONF_MSTR, &modattrs,
3372 debugx(1, DBG_ERR, "configuration error");
3373 addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3377 void getmainconfig(const char *configfile) {
3378 long int loglevel = LONG_MIN;
3379 struct gconffile *cfs;
3381 cfs = openconfigfile(configfile);
3382 memset(&options, 0, sizeof(options));
3384 clconfs = list_create();
3386 debugx(1, DBG_ERR, "malloc failed");
3388 srvconfs = list_create();
3390 debugx(1, DBG_ERR, "malloc failed");
3392 realms = list_create();
3394 debugx(1, DBG_ERR, "malloc failed");
3396 tlsconfs = hash_create();
3398 debugx(1, DBG_ERR, "malloc failed");
3400 rewriteconfs = hash_create();
3402 debugx(1, DBG_ERR, "malloc failed");
3404 if (!getgenericconfig(&cfs, NULL,
3405 "ListenUDP", CONF_MSTR, &options.listenudp,
3406 "ListenTCP", CONF_MSTR, &options.listentcp,
3407 "ListenTLS", CONF_MSTR, &options.listentls,
3408 "ListenDTLS", CONF_MSTR, &options.listendtls,
3409 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
3410 "SourceUDP", CONF_STR, &options.sourceudp,
3411 "SourceTCP", CONF_STR, &options.sourcetcp,
3412 "SourceTLS", CONF_STR, &options.sourcetls,
3413 "SourceDTLS", CONF_STR, &options.sourcedtls,
3414 "LogLevel", CONF_LINT, &loglevel,
3415 "LogDestination", CONF_STR, &options.logdestination,
3416 "LoopPrevention", CONF_BLN, &options.loopprevention,
3417 "Client", CONF_CBK, confclient_cb, NULL,
3418 "Server", CONF_CBK, confserver_cb, NULL,
3419 "Realm", CONF_CBK, confrealm_cb, NULL,
3420 "TLS", CONF_CBK, conftls_cb, NULL,
3421 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3424 debugx(1, DBG_ERR, "configuration error");
3426 if (loglevel != LONG_MIN) {
3427 if (loglevel < 1 || loglevel > 4)
3428 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3429 options.loglevel = (uint8_t)loglevel;
3433 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3436 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3439 *configfile = optarg;
3442 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3443 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3444 *loglevel = *optarg - '0';
3453 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3458 if (!(argc - optind))
3462 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3466 int daemon(int a, int b) {
3474 for (i = 0; i < 3; i++) {
3476 open("/dev/null", O_RDWR);
3482 void *sighandler(void *arg) {
3487 sigemptyset(&sigset);
3488 sigaddset(&sigset, SIGPIPE);
3489 sigwait(&sigset, &sig);
3490 /* only get SIGPIPE right now, so could simplify below code */
3493 /* completely ignoring this */
3496 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3499 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3504 int main(int argc, char **argv) {
3507 struct list_node *entry;
3508 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3509 char *configfile = NULL;
3510 struct clsrvconf *srvconf;
3513 debug_init("radsecproxy");
3514 debug_set_level(DEBUG_LEVEL);
3516 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3518 debug_set_level(loglevel);
3519 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3521 options.loglevel = loglevel;
3522 else if (options.loglevel)
3523 debug_set_level(options.loglevel);
3525 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3526 free(options.logdestination);
3528 if (!list_first(clconfs))
3529 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3530 if (!list_first(realms))
3531 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3534 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3536 if (!foreground && (daemon(0, 0) < 0))
3537 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3539 debug_timestamp_on();
3540 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3542 sigemptyset(&sigset);
3543 /* exit on all but SIGPIPE, ignore more? */
3544 sigaddset(&sigset, SIGPIPE);
3545 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3546 pthread_create(&sigth, NULL, sighandler, NULL);
3548 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3549 srvconf = (struct clsrvconf *)entry->data;
3550 if (srvconf->dynamiclookupcommand)
3552 if (!addserver(srvconf))
3553 debugx(1, DBG_ERR, "failed to add server");
3554 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3555 (void *)(srvconf->servers)))
3556 debugx(1, DBG_ERR, "pthread_create failed");
3558 /* srcprotores for UDP no longer needed */
3559 if (srcprotores[RAD_UDP]) {
3560 freeaddrinfo(srcprotores[RAD_UDP]);
3561 srcprotores[RAD_UDP] = NULL;
3564 for (i = 0; protodefs[i].name; i++)
3565 if (protodefs[i].initextra)
3566 protodefs[i].initextra();
3568 if (find_clconf_type(RAD_TCP, NULL))
3569 createlisteners(RAD_TCP, options.listentcp);
3571 if (find_clconf_type(RAD_TLS, NULL))
3572 createlisteners(RAD_TLS, options.listentls);
3574 if (find_clconf_type(RAD_DTLS, NULL))
3575 createlisteners(RAD_DTLS, options.listendtls);
3577 if (find_clconf_type(RAD_UDP, NULL)) {
3578 createlisteners(RAD_UDP, options.listenudp);
3579 if (options.listenaccudp)
3580 createlisteners(RAD_UDP, options.listenaccudp);
3583 /* just hang around doing nothing, anything to do here? */