2 * Copyright (C) 2006-2008 Stig Venaas <venaas@uninett.no>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
9 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
10 * rd is responsible for init and launching wr
11 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
12 * each tlsserverrd launches tlsserverwr
13 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
14 * for init and launching rd
16 * serverrd will receive a request, processes it and puts it in the requestq of
17 * the appropriate clientwr
18 * clientwr monitors its requestq and sends requests
19 * clientrd looks for responses, processes them and puts them in the replyq of
20 * the peer the request came from
21 * serverwr monitors its reply and sends replies
23 * In addition to the main thread, we have:
24 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
25 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
26 * For each TLS peer connecting to us there will be 2 more TLS threads
27 * This is only for connected peers
28 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
29 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
33 * TCP accounting not yet supported
34 * We are not removing client requests from dynamic servers, see removeclientrqs()
38 #include <sys/socket.h>
39 #include <netinet/in.h>
48 #include <sys/types.h>
49 #include <sys/select.h>
52 #include <arpa/inet.h>
56 #include <openssl/ssl.h>
57 #include <openssl/rand.h>
58 #include <openssl/err.h>
59 #include <openssl/md5.h>
60 #include <openssl/hmac.h>
61 #include <openssl/x509v3.h>
67 #include "radsecproxy.h"
73 static struct options options;
74 static struct list *clconfs, *srvconfs;
76 struct hash *tlsconfs, *rewriteconfs;
78 static struct addrinfo *srcprotores[4] = { NULL, NULL, NULL, NULL };
80 static pthread_mutex_t *ssl_locks = NULL;
81 static long *ssl_lock_count;
85 /* minimum required declarations to avoid reordering code */
86 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
87 int dynamicconfig(struct server *server);
88 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
89 void freerealm(struct realm *realm);
90 void freeclsrvconf(struct clsrvconf *conf);
91 void freerqdata(struct request *rq);
93 static const struct protodefs protodefs[] = {
94 { "udp", /* UDP, assuming RAD_UDP defined as 0 */
95 NULL, /* secretdefault */
96 SOCK_DGRAM, /* socktype */
97 "1812", /* portdefault */
98 REQUEST_RETRY_COUNT, /* retrycountdefault */
99 10, /* retrycountmax */
100 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
101 60, /* retryintervalmax */
102 udpserverrd, /* listener */
103 &options.sourceudp, /* srcaddrport */
104 NULL, /* connecter */
105 NULL, /* clientconnreader */
106 clientradputudp, /* clientradput */
107 addclientudp, /* addclient */
108 addserverextraudp, /* addserverextra */
109 initextraudp /* initextra */
111 { "tls", /* TLS, assuming RAD_TLS defined as 1 */
112 "mysecret", /* secretdefault */
113 SOCK_STREAM, /* socktype */
114 "2083", /* portdefault */
115 0, /* retrycountdefault */
116 0, /* retrycountmax */
117 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
118 60, /* retryintervalmax */
119 tlslistener, /* listener */
120 &options.sourcetls, /* srcaddrport */
121 tlsconnect, /* connecter */
122 tlsclientrd, /* clientconnreader */
123 clientradputtls, /* clientradput */
124 NULL, /* addclient */
125 NULL, /* addserverextra */
128 { "tcp", /* TCP, assuming RAD_TCP defined as 2 */
129 NULL, /* secretdefault */
130 SOCK_STREAM, /* socktype */
131 "1812", /* portdefault */
132 0, /* retrycountdefault */
133 0, /* retrycountmax */
134 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
135 60, /* retryintervalmax */
136 tcplistener, /* listener */
137 &options.sourcetcp, /* srcaddrport */
138 tcpconnect, /* connecter */
139 tcpclientrd, /* clientconnreader */
140 clientradputtcp, /* clientradput */
141 NULL, /* addclient */
142 NULL, /* addserverextra */
145 { "dtls", /* DTLS, assuming RAD_DTLS defined as 3 */
146 "mysecret", /* secretdefault */
147 SOCK_DGRAM, /* socktype */
148 "2083", /* portdefault */
149 REQUEST_RETRY_COUNT, /* retrycountdefault */
150 10, /* retrycountmax */
151 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
152 60, /* retryintervalmax */
153 udpdtlsserverrd, /* listener */
154 &options.sourcedtls, /* srcaddrport */
155 dtlsconnect, /* connecter */
156 dtlsclientrd, /* clientconnreader */
157 clientradputdtls, /* clientradput */
158 addclientdtls, /* addclient */
159 addserverextradtls, /* addserverextra */
160 initextradtls /* initextra */
166 uint8_t protoname2int(const char *name) {
169 for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
173 /* callbacks for making OpenSSL thread safe */
174 unsigned long ssl_thread_id() {
175 return (unsigned long)pthread_self();
178 void ssl_locking_callback(int mode, int type, const char *file, int line) {
179 if (mode & CRYPTO_LOCK) {
180 pthread_mutex_lock(&ssl_locks[type]);
181 ssl_lock_count[type]++;
183 pthread_mutex_unlock(&ssl_locks[type]);
186 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
187 int pwdlen = strlen(userdata);
188 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
190 memcpy(buf, userdata, pwdlen);
194 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
199 err_cert = X509_STORE_CTX_get_current_cert(ctx);
200 err = X509_STORE_CTX_get_error(ctx);
201 depth = X509_STORE_CTX_get_error_depth(ctx);
203 if (depth > MAX_CERT_DEPTH) {
205 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
206 X509_STORE_CTX_set_error(ctx, err);
210 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
211 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
214 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
215 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
216 debug(DBG_WARN, "\tIssuer=%s", buf);
218 case X509_V_ERR_CERT_NOT_YET_VALID:
219 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
220 debug(DBG_WARN, "\tCertificate not yet valid");
222 case X509_V_ERR_CERT_HAS_EXPIRED:
223 debug(DBG_WARN, "Certificate has expired");
225 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
226 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
231 printf("certificate verify returns %d\n", ok);
236 struct addrinfo *getsrcprotores(uint8_t type) {
237 return srcprotores[type];
240 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
241 struct addrinfo hints, *addrinfo, *res;
245 slash = conf->host ? strchr(conf->host, '/') : NULL;
249 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
253 if (*s < '0' || *s > '9') {
254 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
257 plen = atoi(slash + 1);
258 if (plen < 0 || plen > 128) {
259 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
264 memset(&hints, 0, sizeof(hints));
265 hints.ai_socktype = conf->pdef->socktype;
266 hints.ai_family = AF_UNSPEC;
267 hints.ai_flags = ai_flags;
268 if (!conf->host && !conf->port) {
269 /* getaddrinfo() doesn't like host and port to be NULL */
270 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
271 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
274 for (res = addrinfo; res; res = res->ai_next) {
275 switch (res->ai_family) {
277 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
280 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
286 hints.ai_flags |= AI_NUMERICHOST;
287 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
288 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
293 switch (addrinfo->ai_family) {
296 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
297 freeaddrinfo(addrinfo);
304 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
305 freeaddrinfo(addrinfo);
308 conf->prefixlen = plen;
310 conf->prefixlen = 255;
313 freeaddrinfo(conf->addrinfo);
314 conf->addrinfo = addrinfo;
318 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
323 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
327 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
329 debugx(1, DBG_ERR, "no ] matching initial [");
333 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
336 debugx(1, DBG_ERR, "missing host/address");
338 conf->host = stringcopy(field, p - field);
341 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
342 debugx(1, DBG_ERR, "unexpected character after ]");
345 /* port number or service name is specified */;
347 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
349 debugx(1, DBG_ERR, "syntax error, : but no following port");
350 conf->port = stringcopy(field, p - field);
352 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
356 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
357 struct clsrvconf *conf;
359 conf = malloc(sizeof(struct clsrvconf));
361 debugx(1, DBG_ERR, "malloc failed");
362 memset(conf, 0, sizeof(struct clsrvconf));
364 conf->pdef = &protodefs[conf->type];
366 parsehostport(lconf, conf, default_port);
367 if (!strcmp(conf->host, "*")) {
372 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
373 if (!resolvepeer(conf, AI_PASSIVE))
374 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
378 void freeclsrvres(struct clsrvconf *res) {
382 freeaddrinfo(res->addrinfo);
386 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
388 struct addrinfo *res;
390 for (res = addrinfo; res; res = res->ai_next) {
391 if (family != AF_UNSPEC && family != res->ai_family)
393 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
395 debug(DBG_WARN, "bindtoaddr: socket failed");
399 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
402 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
404 if (!bind(s, res->ai_addr, res->ai_addrlen))
406 debug(DBG_WARN, "bindtoaddr: bind failed");
412 int connecttcp(struct addrinfo *addrinfo, struct addrinfo *src) {
414 struct addrinfo *res;
417 for (res = addrinfo; res; res = res->ai_next) {
418 s = bindtoaddr(src, res->ai_family, 1, 1);
420 debug(DBG_WARN, "connecttoserver: socket failed");
423 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
425 debug(DBG_WARN, "connecttoserver: connect failed");
432 /* returns 1 if the len first bits are equal, else 0 */
433 int prefixmatch(void *a1, void *a2, uint8_t len) {
434 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
436 if (l && memcmp(a1, a2, l))
441 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
444 /* returns next config with matching address, or NULL */
445 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
446 struct sockaddr_in6 *sa6 = NULL;
447 struct in_addr *a4 = NULL;
448 struct addrinfo *res;
449 struct list_node *entry;
450 struct clsrvconf *conf;
452 if (addr->sa_family == AF_INET6) {
453 sa6 = (struct sockaddr_in6 *)addr;
454 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
455 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
459 a4 = &((struct sockaddr_in *)addr)->sin_addr;
461 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
462 conf = (struct clsrvconf *)entry->data;
463 if (conf->type == type) {
464 if (conf->prefixlen == 255) {
465 for (res = conf->addrinfo; res; res = res->ai_next)
466 if ((a4 && res->ai_family == AF_INET &&
467 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
468 (sa6 && res->ai_family == AF_INET6 &&
469 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
475 res = conf->addrinfo;
477 ((a4 && res->ai_family == AF_INET &&
478 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
479 (sa6 && res->ai_family == AF_INET6 &&
480 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
491 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
492 return find_conf(type, addr, clconfs, cur);
495 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
496 return find_conf(type, addr, srvconfs, cur);
499 /* returns next config of given type, or NULL */
500 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
501 struct list_node *entry;
502 struct clsrvconf *conf;
504 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
505 conf = (struct clsrvconf *)entry->data;
506 if (conf->type == type) {
515 struct queue *newqueue() {
518 q = malloc(sizeof(struct queue));
520 debugx(1, DBG_ERR, "malloc failed");
521 q->entries = list_create();
523 debugx(1, DBG_ERR, "malloc failed");
524 pthread_mutex_init(&q->mutex, NULL);
525 pthread_cond_init(&q->cond, NULL);
529 void removequeue(struct queue *q) {
530 struct list_node *entry;
532 pthread_mutex_lock(&q->mutex);
533 for (entry = list_first(q->entries); entry; entry = list_next(entry))
534 free(((struct reply *)entry)->buf);
535 list_destroy(q->entries);
536 pthread_cond_destroy(&q->cond);
537 pthread_mutex_unlock(&q->mutex);
538 pthread_mutex_destroy(&q->mutex);
541 void freebios(struct queue *q) {
544 pthread_mutex_lock(&q->mutex);
545 while ((bio = (BIO *)list_shift(q->entries)))
547 pthread_mutex_unlock(&q->mutex);
551 struct client *addclient(struct clsrvconf *conf) {
552 struct client *new = malloc(sizeof(struct client));
555 debug(DBG_ERR, "malloc failed");
558 if (!conf->clients) {
559 conf->clients = list_create();
560 if (!conf->clients) {
561 debug(DBG_ERR, "malloc failed");
566 memset(new, 0, sizeof(struct client));
568 if (conf->pdef->addclient)
569 conf->pdef->addclient(new);
571 new->replyq = newqueue();
572 list_push(conf->clients, new);
576 void removeclient(struct client *client) {
577 if (!client || !client->conf->clients)
579 removequeue(client->replyq);
581 freebios(client->rbios);
582 list_removedata(client->conf->clients, client);
586 void removeclientrqs(struct client *client) {
587 struct list_node *entry;
588 struct server *server;
592 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
593 server = ((struct clsrvconf *)entry->data)->servers;
596 pthread_mutex_lock(&server->newrq_mutex);
597 for (i = 0; i < MAX_REQUESTS; i++) {
598 rq = server->requests + i;
599 if (rq->from == client)
602 pthread_mutex_unlock(&server->newrq_mutex);
606 void freeserver(struct server *server, uint8_t destroymutex) {
607 struct request *rq, *end;
612 if (server->requests) {
613 rq = server->requests;
614 for (end = rq + MAX_REQUESTS; rq < end; rq++)
616 free(server->requests);
619 freebios(server->rbios);
620 free(server->dynamiclookuparg);
622 pthread_mutex_destroy(&server->lock);
623 pthread_cond_destroy(&server->newrq_cond);
624 pthread_mutex_destroy(&server->newrq_mutex);
629 int addserver(struct clsrvconf *conf) {
630 struct clsrvconf *res;
634 debug(DBG_ERR, "addserver: currently works with just one server per conf");
637 conf->servers = malloc(sizeof(struct server));
638 if (!conf->servers) {
639 debug(DBG_ERR, "malloc failed");
642 memset(conf->servers, 0, sizeof(struct server));
643 conf->servers->conf = conf;
646 if (type == RAD_DTLS)
647 conf->servers->rbios = newqueue();
649 if (!srcprotores[type]) {
650 res = resolve_hostport(type, *conf->pdef->srcaddrport, NULL);
651 srcprotores[type] = res->addrinfo;
652 res->addrinfo = NULL;
656 conf->servers->sock = -1;
657 if (conf->pdef->addserverextra)
658 conf->pdef->addserverextra(conf);
660 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
661 if (!conf->servers->requests) {
662 debug(DBG_ERR, "malloc failed");
665 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
666 debug(DBG_ERR, "mutex init failed");
669 conf->servers->newrq = 0;
670 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
671 debug(DBG_ERR, "mutex init failed");
672 pthread_mutex_destroy(&conf->servers->lock);
675 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
676 debug(DBG_ERR, "mutex init failed");
677 pthread_mutex_destroy(&conf->servers->newrq_mutex);
678 pthread_mutex_destroy(&conf->servers->lock);
685 freeserver(conf->servers, 0);
686 conf->servers = NULL;
690 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
691 int loc, i, l, n, r = 0;
694 STACK_OF(GENERAL_NAME) *alt;
697 debug(DBG_DBG, "subjectaltnameaddr");
699 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
703 ex = X509_get_ext(cert, loc);
704 alt = X509V3_EXT_d2i(ex);
708 n = sk_GENERAL_NAME_num(alt);
709 for (i = 0; i < n; i++) {
710 gn = sk_GENERAL_NAME_value(alt, i);
711 if (gn->type != GEN_IPADD)
714 v = (char *)ASN1_STRING_data(gn->d.ia5);
715 l = ASN1_STRING_length(gn->d.ia5);
716 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
717 && !memcmp(v, &addr, l)) {
722 GENERAL_NAMES_free(alt);
726 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
733 nm = X509_get_subject_name(cert);
736 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
739 e = X509_NAME_get_entry(nm, loc);
740 t = X509_NAME_ENTRY_get_data(e);
741 v = (char *) ASN1_STRING_data(t);
742 l = ASN1_STRING_length(t);
746 if (l == strlen(exact) && !strncasecmp(exact, v, l))
749 s = stringcopy((char *)v, l);
751 debug(DBG_ERR, "malloc failed");
754 if (regexec(regex, s, 0, NULL, 0)) {
765 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
766 int loc, i, l, n, r = 0;
769 STACK_OF(GENERAL_NAME) *alt;
772 debug(DBG_DBG, "subjectaltnameregexp");
774 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
778 ex = X509_get_ext(cert, loc);
779 alt = X509V3_EXT_d2i(ex);
783 n = sk_GENERAL_NAME_num(alt);
784 for (i = 0; i < n; i++) {
785 gn = sk_GENERAL_NAME_value(alt, i);
786 if (gn->type != type)
789 v = (char *)ASN1_STRING_data(gn->d.ia5);
790 l = ASN1_STRING_length(gn->d.ia5);
794 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
797 if (memcmp(v, exact, l))
800 s = stringcopy((char *)v, l);
802 debug(DBG_ERR, "malloc failed");
805 if (regexec(regex, s, 0, NULL, 0)) {
814 GENERAL_NAMES_free(alt);
818 X509 *verifytlscert(SSL *ssl) {
822 if (SSL_get_verify_result(ssl) != X509_V_OK) {
823 debug(DBG_ERR, "verifytlscert: basic validation failed");
824 while ((error = ERR_get_error()))
825 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
829 cert = SSL_get_peer_certificate(ssl);
831 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
835 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
837 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
838 struct in6_addr addr;
840 if (conf->certnamecheck && conf->prefixlen == 255) {
841 if (inet_pton(AF_INET, conf->host, &addr))
843 else if (inet_pton(AF_INET6, conf->host, &addr))
846 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
849 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
852 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
854 if (!cnregexp(cert, conf->host, NULL)) {
855 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
858 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
861 if (conf->certcnregex) {
862 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
863 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
866 debug(DBG_DBG, "verifyconfcert: CN matching regex");
868 if (conf->certuriregex) {
869 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
870 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
873 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
878 int radsign(unsigned char *rad, unsigned char *sec) {
879 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
880 static unsigned char first = 1;
881 static EVP_MD_CTX mdctx;
885 pthread_mutex_lock(&lock);
887 EVP_MD_CTX_init(&mdctx);
891 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
892 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
893 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
894 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
896 pthread_mutex_unlock(&lock);
900 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
901 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
902 static unsigned char first = 1;
903 static EVP_MD_CTX mdctx;
904 unsigned char hash[EVP_MAX_MD_SIZE];
908 pthread_mutex_lock(&lock);
910 EVP_MD_CTX_init(&mdctx);
916 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
917 EVP_DigestUpdate(&mdctx, rad, 4) &&
918 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
919 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
920 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
921 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
923 !memcmp(hash, rad + 4, 16));
924 pthread_mutex_unlock(&lock);
928 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
929 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
930 static unsigned char first = 1;
931 static HMAC_CTX hmacctx;
933 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
935 pthread_mutex_lock(&lock);
937 HMAC_CTX_init(&hmacctx);
941 memcpy(auth, authattr, 16);
942 memset(authattr, 0, 16);
944 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
945 HMAC_Update(&hmacctx, rad, RADLEN(rad));
946 HMAC_Final(&hmacctx, hash, &md_len);
947 memcpy(authattr, auth, 16);
949 debug(DBG_WARN, "message auth computation failed");
950 pthread_mutex_unlock(&lock);
954 if (memcmp(auth, hash, 16)) {
955 debug(DBG_WARN, "message authenticator, wrong value");
956 pthread_mutex_unlock(&lock);
960 pthread_mutex_unlock(&lock);
964 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
965 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
966 static unsigned char first = 1;
967 static HMAC_CTX hmacctx;
973 pthread_mutex_lock(&lock);
975 HMAC_CTX_init(&hmacctx);
979 memset(authattrval, 0, 16);
981 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
982 HMAC_Update(&hmacctx, rad, RADLEN(rad));
983 HMAC_Final(&hmacctx, authattrval, &md_len);
985 debug(DBG_WARN, "message auth computation failed");
986 pthread_mutex_unlock(&lock);
990 pthread_mutex_unlock(&lock);
994 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
996 if (ATTRTYPE(attrs) == type)
998 length -= ATTRLEN(attrs);
999 attrs += ATTRLEN(attrs);
1004 void freerqdata(struct request *rq) {
1005 if (rq->origusername)
1006 free(rq->origusername);
1011 void sendrq(struct server *to, struct request *rq) {
1015 pthread_mutex_lock(&to->newrq_mutex);
1016 /* might simplify if only try nextid, might be ok */
1017 for (i = to->nextid; i < MAX_REQUESTS; i++)
1018 if (!to->requests[i].buf)
1020 if (i == MAX_REQUESTS) {
1021 for (i = 0; i < to->nextid; i++)
1022 if (!to->requests[i].buf)
1024 if (i == to->nextid) {
1025 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
1031 rq->buf[1] = (char)i;
1033 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1034 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1039 if (*rq->buf == RAD_Accounting_Request) {
1040 if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
1041 debug(DBG_WARN, "sendrq: failed to sign Accounting-Request message");
1047 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1048 to->requests[i] = *rq;
1053 debug(DBG_DBG, "sendrq: signalling client writer");
1054 pthread_cond_signal(&to->newrq_cond);
1057 pthread_mutex_unlock(&to->newrq_mutex);
1060 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa, int toudpsock) {
1061 struct reply *reply;
1064 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1066 debug(DBG_WARN, "sendreply: failed to sign message");
1070 reply = malloc(sizeof(struct reply));
1073 debug(DBG_ERR, "sendreply: malloc failed");
1076 memset(reply, 0, sizeof(struct reply));
1079 reply->tosa = *tosa;
1080 reply->toudpsock = toudpsock;
1082 pthread_mutex_lock(&to->replyq->mutex);
1084 first = list_first(to->replyq->entries) == NULL;
1086 if (!list_push(to->replyq->entries, reply)) {
1087 pthread_mutex_unlock(&to->replyq->mutex);
1090 debug(DBG_ERR, "sendreply: malloc failed");
1095 debug(DBG_DBG, "signalling server writer");
1096 pthread_cond_signal(&to->replyq->cond);
1098 pthread_mutex_unlock(&to->replyq->mutex);
1101 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1102 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1103 static unsigned char first = 1;
1104 static EVP_MD_CTX mdctx;
1105 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1106 unsigned int md_len;
1107 uint8_t i, offset = 0, out[128];
1109 pthread_mutex_lock(&lock);
1111 EVP_MD_CTX_init(&mdctx);
1117 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1118 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1119 !EVP_DigestUpdate(&mdctx, input, 16) ||
1120 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1122 pthread_mutex_unlock(&lock);
1125 for (i = 0; i < 16; i++)
1126 out[offset + i] = hash[i] ^ in[offset + i];
1127 input = out + offset - 16;
1132 memcpy(in, out, len);
1133 pthread_mutex_unlock(&lock);
1137 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1138 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1139 static unsigned char first = 1;
1140 static EVP_MD_CTX mdctx;
1141 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1142 unsigned int md_len;
1143 uint8_t i, offset = 0, out[128];
1145 pthread_mutex_lock(&lock);
1147 EVP_MD_CTX_init(&mdctx);
1153 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1154 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1155 !EVP_DigestUpdate(&mdctx, input, 16) ||
1156 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1158 pthread_mutex_unlock(&lock);
1161 for (i = 0; i < 16; i++)
1162 out[offset + i] = hash[i] ^ in[offset + i];
1163 input = in + offset;
1168 memcpy(in, out, len);
1169 pthread_mutex_unlock(&lock);
1173 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1174 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1175 static unsigned char first = 1;
1176 static EVP_MD_CTX mdctx;
1177 unsigned char hash[EVP_MAX_MD_SIZE];
1178 unsigned int md_len;
1181 pthread_mutex_lock(&lock);
1183 EVP_MD_CTX_init(&mdctx);
1188 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1189 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1190 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1193 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1194 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1195 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1196 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1197 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1198 pthread_mutex_unlock(&lock);
1203 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1206 for (i = 0; i < 16; i++)
1209 for (offset = 16; offset < len; offset += 16) {
1211 printf("text + offset - 16 c(%d): ", offset / 16);
1212 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1214 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1215 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1216 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1217 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1219 pthread_mutex_unlock(&lock);
1223 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1226 for (i = 0; i < 16; i++)
1227 text[offset + i] ^= hash[i];
1231 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1234 pthread_mutex_unlock(&lock);
1238 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1239 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1240 static unsigned char first = 1;
1241 static EVP_MD_CTX mdctx;
1242 unsigned char hash[EVP_MAX_MD_SIZE];
1243 unsigned int md_len;
1247 pthread_mutex_lock(&lock);
1249 EVP_MD_CTX_init(&mdctx);
1254 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1255 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1256 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1259 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1260 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1261 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1262 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1263 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1264 pthread_mutex_unlock(&lock);
1269 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1272 for (i = 0; i < 16; i++)
1273 plain[i] = text[i] ^ hash[i];
1275 for (offset = 16; offset < len; offset += 16) {
1277 printf("text + offset - 16 c(%d): ", offset / 16);
1278 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1280 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1281 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1282 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1283 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1285 pthread_mutex_unlock(&lock);
1289 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1292 for (i = 0; i < 16; i++)
1293 plain[offset + i] = text[offset + i] ^ hash[i];
1296 memcpy(text, plain, len);
1298 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1301 pthread_mutex_unlock(&lock);
1305 struct realm *id2realm(struct list *realmlist, char *id) {
1306 struct list_node *entry;
1307 struct realm *realm, *subrealm = NULL;
1309 /* need to do locking for subrealms and check subrealm timers */
1310 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1311 realm = (struct realm *)entry->data;
1312 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1313 pthread_mutex_lock(&realm->subrealms_mutex);
1314 if (realm->subrealms)
1315 subrealm = id2realm(realm->subrealms, id);
1316 pthread_mutex_unlock(&realm->subrealms_mutex);
1317 return subrealm ? subrealm : realm;
1323 /* helper function, only used by removeserversubrealms() */
1324 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1325 struct list_node *entry;
1326 struct realm *realm;
1328 for (entry = list_first(realmlist); entry;) {
1329 realm = (struct realm *)entry->data;
1330 entry = list_next(entry);
1331 if (realm->srvconfs) {
1332 list_removedata(realm->srvconfs, srv);
1333 if (!list_first(realm->srvconfs)) {
1334 list_destroy(realm->srvconfs);
1335 realm->srvconfs = NULL;
1338 if (realm->accsrvconfs) {
1339 list_removedata(realm->accsrvconfs, srv);
1340 if (!list_first(realm->accsrvconfs)) {
1341 list_destroy(realm->accsrvconfs);
1342 realm->accsrvconfs = NULL;
1346 /* remove subrealm if no servers */
1347 if (!realm->srvconfs && !realm->accsrvconfs) {
1348 list_removedata(realmlist, realm);
1354 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1355 struct list_node *entry;
1356 struct realm *realm;
1358 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1359 realm = (struct realm *)entry->data;
1360 pthread_mutex_lock(&realm->subrealms_mutex);
1361 if (realm->subrealms) {
1362 _internal_removeserversubrealms(realm->subrealms, srv);
1363 if (!list_first(realm->subrealms)) {
1364 list_destroy(realm->subrealms);
1365 realm->subrealms = NULL;
1368 pthread_mutex_unlock(&realm->subrealms_mutex);
1372 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1373 struct request *rq = to->requests, *end;
1375 pthread_mutex_lock(&to->newrq_mutex);
1376 for (end = rq + MAX_REQUESTS; rq < end; rq++)
1377 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1379 pthread_mutex_unlock(&to->newrq_mutex);
1384 int attrvalidate(unsigned char *attrs, int length) {
1385 while (length > 1) {
1386 if (ATTRLEN(attrs) < 2) {
1387 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1390 length -= ATTRLEN(attrs);
1392 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1395 attrs += ATTRLEN(attrs);
1398 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1402 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1403 if (len < 16 || len > 128 || len % 16) {
1404 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1408 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1409 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1413 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1415 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1416 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1422 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1425 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1426 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1429 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1430 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1436 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1437 char *oldsecret, char *newsecret) {
1438 unsigned char *attr;
1440 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1441 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1442 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1448 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1452 for (; attrs[0]; attrs += 2)
1453 if (attrs[0] == vendor && attrs[1] == subattr)
1458 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1459 uint8_t alen, sublen, rmlen = 0;
1460 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1463 if (!removevendorattrs)
1466 while (*removevendorattrs && *removevendorattrs != vendor)
1467 removevendorattrs += 2;
1468 if (!*removevendorattrs)
1471 alen = ATTRLEN(attrs);
1473 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1474 /* remove entire vendor attribute */
1475 memmove(attrs, attrs + alen, length - alen);
1480 subattrs = ATTRVAL(attrs) + 4;
1482 if (!attrvalidate(subattrs, sublen)) {
1483 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1488 while (sublen > 1) {
1489 alen = ATTRLEN(subattrs);
1492 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1493 memmove(subattrs, subattrs + alen, length);
1499 ATTRLEN(attrs) -= rmlen;
1503 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1504 uint8_t *attrs, alen;
1505 uint16_t len, rmlen = 0;
1507 if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1510 len = RADLEN(buf) - 20;
1513 alen = ATTRLEN(attrs);
1515 if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1516 memmove(attrs, attrs + alen, len);
1518 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1519 rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1524 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1527 /* returns a pointer to the resized attribute value */
1528 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1529 uint8_t *attrs, *attr, vallen;
1533 len = RADLEN(*buf) - 20;
1536 attr = attrget(attrs, len, type);
1540 vallen = ATTRVALLEN(attr);
1541 if (vallen == newvallen)
1544 len += newvallen - vallen;
1545 if (newvallen > vallen) {
1546 new = realloc(*buf, len + 20);
1548 debug(DBG_ERR, "resizeattr: malloc failed");
1557 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1558 attr[1] = newvallen + 2;
1559 ((uint16_t *)*buf)[1] = htons(len + 20);
1563 int rewriteusername(struct request *rq, char *in) {
1564 size_t nmatch = 10, reslen = 0, start = 0;
1565 regmatch_t pmatch[10], *pfield;
1567 unsigned char *result;
1568 char *out = rq->from->conf->rewriteattrreplacement;
1570 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1571 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1575 rq->origusername = stringcopy(in, 0);
1576 if (!rq->origusername)
1579 for (i = start; out[i]; i++) {
1580 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1581 pfield = &pmatch[out[i + 1] - '0'];
1582 if (pfield->rm_so >= 0) {
1583 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1589 reslen += i - start;
1591 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1597 for (i = start; out[i]; i++) {
1598 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1599 pfield = &pmatch[out[i + 1] - '0'];
1600 if (pfield->rm_so >= 0) {
1601 memcpy(result + reslen, out + start, i - start);
1602 reslen += i - start;
1603 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1604 reslen += pfield->rm_eo - pfield->rm_so;
1611 memcpy(result + reslen, out + start, i - start);
1612 reslen += i - start;
1613 memcpy(in, result, reslen);
1618 const char *radmsgtype2string(uint8_t code) {
1619 static const char *rad_msg_names[] = {
1620 "", "Access-Request", "Access-Accept", "Access-Reject",
1621 "Accounting-Request", "Accounting-Response", "", "",
1622 "", "", "", "Access-Challenge",
1623 "Status-Server", "Status-Client"
1625 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1628 void char2hex(char *h, unsigned char c) {
1629 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1630 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1631 h[0] = hexdigits[c / 16];
1632 h[1] = hexdigits[c % 16];
1636 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
1640 if (!attr || len == 1) {
1645 l = ATTRVALLEN(attr);
1646 s = (char *)ATTRVAL(attr);
1649 for (i = 0; i < l; i++) {
1650 if (s[i] > 31 && s[i] < 127) {
1652 if (d - ascii == len - 1)
1655 if (d - ascii > len - 4)
1660 if (d - ascii == len - 1)
1668 void acclog(unsigned char *attrs, int length, char *host) {
1669 unsigned char *attr;
1672 attr = attrget(attrs, length, RAD_Attr_User_Name);
1674 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1677 radattr2ascii(username, sizeof(username), attr);
1678 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1681 void respondaccounting(struct request *rq) {
1682 unsigned char *resp;
1686 debug(DBG_ERR, "respondaccounting: malloc failed");
1689 memcpy(resp, rq->buf, 20);
1690 resp[0] = RAD_Accounting_Response;
1693 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1694 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1697 void respondstatusserver(struct request *rq) {
1698 unsigned char *resp;
1702 debug(DBG_ERR, "respondstatusserver: malloc failed");
1705 memcpy(resp, rq->buf, 20);
1706 resp[0] = RAD_Access_Accept;
1709 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1710 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1713 void respondreject(struct request *rq, char *message) {
1714 unsigned char *resp;
1717 if (message && *message)
1718 len += 2 + strlen(message);
1722 debug(DBG_ERR, "respondreject: malloc failed");
1725 memcpy(resp, rq->buf, 20);
1726 resp[0] = RAD_Access_Reject;
1727 *(uint16_t *)(resp + 2) = htons(len);
1728 if (message && *message) {
1729 resp[20] = RAD_Attr_Reply_Message;
1730 resp[21] = len - 20;
1731 memcpy(resp + 22, message, len - 22);
1733 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1736 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1737 struct list_node *entry;
1738 struct clsrvconf *server, *best = NULL, *first = NULL;
1740 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1741 server = (struct clsrvconf *)entry->data;
1742 if (!server->servers)
1746 if (!server->servers->connectionok)
1748 if (!server->servers->lostrqs)
1754 if (server->servers->lostrqs < best->servers->lostrqs)
1757 return best ? best : first;
1760 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
1761 struct clsrvconf *srvconf;
1763 *realm = id2realm(realms, id);
1766 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1767 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1770 if (!acc && !srvconf->servers)
1771 adddynamicrealmserver(*realm, srvconf, id);
1772 return srvconf->servers;
1775 /* returns 0 if validation/authentication fails, else 1 */
1776 int radsrv(struct request *rq) {
1777 uint8_t code, id, *auth, *attrs, *attr;
1779 struct server *to = NULL;
1780 char username[254], userascii[760];
1781 unsigned char newauth[16];
1782 struct realm *realm = NULL;
1784 code = *(uint8_t *)rq->buf;
1785 id = *(uint8_t *)(rq->buf + 1);
1786 len = RADLEN(rq->buf);
1787 auth = (uint8_t *)(rq->buf + 4);
1789 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1791 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1792 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1797 attrs = rq->buf + 20;
1799 if (!attrvalidate(attrs, len)) {
1800 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1804 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1805 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
1806 debug(DBG_WARN, "radsrv: message authentication failed");
1810 if (code == RAD_Status_Server) {
1811 respondstatusserver(rq);
1815 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1817 if (code == RAD_Accounting_Request) {
1818 memset(newauth, 0, 16);
1819 if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
1820 debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
1825 if (rq->from->conf->rewrite) {
1826 dorewrite(rq->buf, rq->from->conf->rewrite);
1827 len = RADLEN(rq->buf) - 20;
1830 attr = attrget(attrs, len, RAD_Attr_User_Name);
1832 if (code == RAD_Accounting_Request) {
1833 acclog(attrs, len, rq->from->conf->host);
1834 respondaccounting(rq);
1836 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1839 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1840 username[ATTRVALLEN(attr)] = '\0';
1841 radattr2ascii(userascii, sizeof(userascii), attr);
1843 if (rq->from->conf->rewriteattrregex) {
1844 if (!rewriteusername(rq, username)) {
1845 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1848 len = RADLEN(rq->buf) - 20;
1849 auth = (uint8_t *)(rq->buf + 4);
1850 attrs = rq->buf + 20;
1853 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
1855 to = findserver(&realm, username, code == RAD_Accounting_Request);
1857 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1861 if (realm->message && code == RAD_Access_Request) {
1862 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
1863 respondreject(rq, realm->message);
1864 } else if (realm->accresp && code == RAD_Accounting_Request) {
1865 acclog(attrs, len, rq->from->conf->host);
1866 respondaccounting(rq);
1871 if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
1872 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
1873 rq->from->conf->name, to->conf->name);
1877 if (rqinqueue(to, rq->from, id, code)) {
1878 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
1879 radmsgtype2string(code), rq->from->conf->host, id);
1883 if (code != RAD_Accounting_Request) {
1884 if (!RAND_bytes(newauth, 16)) {
1885 debug(DBG_WARN, "radsrv: failed to generate random auth");
1891 printfchars(NULL, "auth", "%02x ", auth, 16);
1894 attr = attrget(attrs, len, RAD_Attr_User_Password);
1896 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1897 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
1901 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1903 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1904 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
1909 memcpy(rq->origauth, auth, 16);
1910 memcpy(auth, newauth, 16);
1923 int replyh(struct server *server, unsigned char *buf) {
1924 struct client *from;
1927 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
1928 struct sockaddr_storage fromsa;
1929 char tmp[760], stationid[760];
1931 server->connectionok = 1;
1932 server->lostrqs = 0;
1934 i = buf[1]; /* i is the id */
1936 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
1937 && *buf != RAD_Accounting_Response) {
1938 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
1941 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
1943 rq = server->requests + i;
1945 pthread_mutex_lock(&server->newrq_mutex);
1946 if (!rq->buf || !rq->tries) {
1947 pthread_mutex_unlock(&server->newrq_mutex);
1948 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
1953 pthread_mutex_unlock(&server->newrq_mutex);
1954 debug(DBG_INFO, "replyh: already received, ignoring reply");
1958 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
1959 pthread_mutex_unlock(&server->newrq_mutex);
1960 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
1964 len = RADLEN(buf) - 20;
1967 if (!attrvalidate(attrs, len)) {
1968 pthread_mutex_unlock(&server->newrq_mutex);
1969 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
1973 /* Message Authenticator */
1974 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1976 if (ATTRVALLEN(messageauth) != 16) {
1977 pthread_mutex_unlock(&server->newrq_mutex);
1978 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
1981 memcpy(tmp, buf + 4, 16);
1982 memcpy(buf + 4, rq->buf + 4, 16);
1983 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
1984 pthread_mutex_unlock(&server->newrq_mutex);
1985 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
1988 memcpy(buf + 4, tmp, 16);
1989 debug(DBG_DBG, "replyh: message auth ok");
1992 gettimeofday(&server->lastrcv, NULL);
1994 if (*rq->buf == RAD_Status_Server) {
1996 pthread_mutex_unlock(&server->newrq_mutex);
1997 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2001 gettimeofday(&server->lastreply, NULL);
2005 pthread_mutex_unlock(&server->newrq_mutex);
2006 debug(DBG_INFO, "replyh: client gone, ignoring reply");
2010 if (server->conf->rewrite) {
2011 dorewrite(buf, server->conf->rewrite);
2012 len = RADLEN(buf) - 20;
2016 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2017 if (ATTRVALLEN(attr) <= 4)
2020 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
2023 sublen = ATTRVALLEN(attr) - 4;
2024 subattrs = ATTRVAL(attr) + 4;
2025 if (!attrvalidate(subattrs, sublen) ||
2026 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2027 rq, server->conf->secret, from->conf->secret) ||
2028 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2029 rq, server->conf->secret, from->conf->secret))
2033 pthread_mutex_unlock(&server->newrq_mutex);
2034 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2038 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2039 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2041 radattr2ascii(tmp, sizeof(tmp), attr);
2042 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2044 radattr2ascii(stationid, sizeof(stationid), attr);
2045 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2046 radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2048 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2052 buf[1] = (char)rq->origid;
2053 memcpy(buf + 4, rq->origauth, 16);
2055 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2058 if (rq->origusername) {
2059 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2061 pthread_mutex_unlock(&server->newrq_mutex);
2062 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2065 memcpy(username, rq->origusername, strlen(rq->origusername));
2066 len = RADLEN(buf) - 20;
2069 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2073 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2074 pthread_mutex_unlock(&server->newrq_mutex);
2075 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2078 debug(DBG_DBG, "replyh: computed messageauthattr");
2081 fromsa = rq->fromsa; /* only needed for UDP */
2082 /* once we set received = 1, rq may be reused */
2085 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2086 sendreply(from, buf, &fromsa, rq->fromudpsock);
2087 pthread_mutex_unlock(&server->newrq_mutex);
2091 /* code for removing state not finished */
2092 void *clientwr(void *arg) {
2093 struct server *server = (struct server *)arg;
2095 pthread_t clientrdth;
2096 int i, dynconffail = 0;
2099 struct timespec timeout;
2100 struct request statsrvrq;
2101 unsigned char statsrvbuf[38];
2102 struct clsrvconf *conf;
2104 conf = server->conf;
2106 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2111 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2112 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2116 memset(&timeout, 0, sizeof(struct timespec));
2118 if (conf->statusserver) {
2119 memset(&statsrvrq, 0, sizeof(struct request));
2120 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2121 statsrvbuf[0] = RAD_Status_Server;
2123 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2124 statsrvbuf[21] = 18;
2125 gettimeofday(&server->lastrcv, NULL);
2128 if (conf->pdef->connecter) {
2129 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2131 server->connectionok = 1;
2132 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
2133 debug(DBG_ERR, "clientwr: pthread_create failed");
2137 server->connectionok = 1;
2140 pthread_mutex_lock(&server->newrq_mutex);
2141 if (!server->newrq) {
2142 gettimeofday(&now, NULL);
2143 /* random 0-7 seconds */
2144 RAND_bytes(&rnd, 1);
2146 if (conf->statusserver) {
2147 if (!timeout.tv_sec || timeout.tv_sec > server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd)
2148 timeout.tv_sec = server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd;
2150 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2151 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2154 if (timeout.tv_sec > now.tv_sec)
2155 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2157 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2160 if (server->newrq) {
2161 debug(DBG_DBG, "clientwr: got new request");
2166 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2168 pthread_mutex_unlock(&server->newrq_mutex);
2170 for (i = 0; i < MAX_REQUESTS; i++) {
2171 if (server->clientrdgone) {
2172 pthread_join(clientrdth, NULL);
2175 pthread_mutex_lock(&server->newrq_mutex);
2176 while (i < MAX_REQUESTS && !server->requests[i].buf)
2178 if (i == MAX_REQUESTS) {
2179 pthread_mutex_unlock(&server->newrq_mutex);
2182 rq = server->requests + i;
2185 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2187 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2189 /* setting this to NULL means that it can be reused */
2192 pthread_mutex_unlock(&server->newrq_mutex);
2196 gettimeofday(&now, NULL);
2197 if (now.tv_sec < rq->expiry.tv_sec) {
2198 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2199 timeout.tv_sec = rq->expiry.tv_sec;
2200 pthread_mutex_unlock(&server->newrq_mutex);
2204 if (rq->tries == (*rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2205 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2206 if (conf->statusserver) {
2207 if (*rq->buf == RAD_Status_Server) {
2208 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2209 if (server->lostrqs < 255)
2213 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2214 if (server->lostrqs < 255)
2218 /* setting this to NULL means that it can be reused */
2220 pthread_mutex_unlock(&server->newrq_mutex);
2223 pthread_mutex_unlock(&server->newrq_mutex);
2225 rq->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2226 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2227 timeout.tv_sec = rq->expiry.tv_sec;
2229 conf->pdef->clientradput(server, server->requests[i].buf);
2231 if (conf->statusserver) {
2232 gettimeofday(&now, NULL);
2233 if (now.tv_sec - server->lastrcv.tv_sec >= STATUS_SERVER_PERIOD) {
2234 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2235 debug(DBG_WARN, "clientwr: failed to generate random auth");
2238 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2239 if (!statsrvrq.buf) {
2240 debug(DBG_ERR, "clientwr: malloc failed");
2243 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2244 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2245 sendrq(server, &statsrvrq);
2250 conf->servers = NULL;
2251 if (server->dynamiclookuparg) {
2252 removeserversubrealms(realms, conf);
2256 freeclsrvconf(conf);
2258 freeserver(server, 1);
2259 ERR_remove_state(0);
2263 void createlistener(uint8_t type, char *arg) {
2265 struct clsrvconf *listenres;
2266 struct addrinfo *res;
2267 int s = -1, on = 1, *sp = NULL;
2269 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2271 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2273 for (res = listenres->addrinfo; res; res = res->ai_next) {
2274 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2276 debug(DBG_WARN, "createlistener: socket failed");
2279 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2281 if (res->ai_family == AF_INET6)
2282 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2284 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2285 debug(DBG_WARN, "createlistener: bind failed");
2291 sp = malloc(sizeof(int));
2293 debugx(1, DBG_ERR, "malloc failed");
2295 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
2296 debugx(1, DBG_ERR, "pthread_create failed");
2300 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2302 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
2303 listenres->host ? listenres->host : "*", listenres->port);
2304 freeclsrvres(listenres);
2307 void createlisteners(uint8_t type, char **args) {
2311 for (i = 0; args[i]; i++)
2312 createlistener(type, args[i]);
2314 createlistener(type, NULL);
2318 void ssl_info_callback(const SSL *ssl, int where, int ret) {
2322 w = where & ~SSL_ST_MASK;
2324 if (w & SSL_ST_CONNECT)
2326 else if (w & SSL_ST_ACCEPT)
2331 if (where & SSL_CB_LOOP)
2332 debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
2333 else if (where & SSL_CB_ALERT) {
2334 s = (where & SSL_CB_READ) ? "read" : "write";
2335 debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
2337 else if (where & SSL_CB_EXIT) {
2339 debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
2341 debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
2346 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2347 SSL_CTX *ctx = NULL;
2348 STACK_OF(X509_NAME) *calist;
2351 unsigned long error;
2354 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2355 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2356 for (i = 0; i < CRYPTO_num_locks(); i++) {
2357 ssl_lock_count[i] = 0;
2358 pthread_mutex_init(&ssl_locks[i], NULL);
2360 CRYPTO_set_id_callback(ssl_thread_id);
2361 CRYPTO_set_locking_callback(ssl_locking_callback);
2363 SSL_load_error_strings();
2366 while (!RAND_status()) {
2367 time_t t = time(NULL);
2368 pid_t pid = getpid();
2369 RAND_seed((unsigned char *)&t, sizeof(time_t));
2370 RAND_seed((unsigned char *)&pid, sizeof(pid));
2376 ctx = SSL_CTX_new(TLSv1_method());
2378 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2382 ctx = SSL_CTX_new(DTLSv1_method());
2384 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2386 SSL_CTX_set_read_ahead(ctx, 1);
2390 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2394 if (conf->certkeypwd) {
2395 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2396 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2398 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2399 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2400 !SSL_CTX_check_private_key(ctx) ||
2401 !SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2402 while ((error = ERR_get_error()))
2403 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2404 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2409 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2410 if (!conf->cacertfile || calist) {
2411 if (conf->cacertpath) {
2413 calist = sk_X509_NAME_new_null();
2414 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2415 sk_X509_NAME_free(calist);
2421 while ((error = ERR_get_error()))
2422 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2423 debug(DBG_ERR, "tlscreatectx: Error adding CA subjects in TLS context %s", conf->name);
2427 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2428 SSL_CTX_set_client_CA_list(ctx, calist);
2430 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2431 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2433 if (conf->crlcheck) {
2434 x509_s = SSL_CTX_get_cert_store(ctx);
2435 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2438 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
2442 SSL_CTX *tlsgetctx(uint8_t type, char *alt1, char *alt2) {
2445 t = hash_read(tlsconfs, alt1, strlen(alt1));
2447 t = hash_read(tlsconfs, alt2, strlen(alt2));
2455 t->tlsctx = tlscreatectx(RAD_TLS, t);
2459 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2465 struct list *addsrvconfs(char *value, char **names) {
2466 struct list *conflist;
2468 struct list_node *entry;
2469 struct clsrvconf *conf = NULL;
2471 if (!names || !*names)
2474 conflist = list_create();
2476 debug(DBG_ERR, "malloc failed");
2480 for (n = 0; names[n]; n++) {
2481 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2482 conf = (struct clsrvconf *)entry->data;
2483 if (!strcasecmp(names[n], conf->name))
2487 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2488 list_destroy(conflist);
2491 if (!list_push(conflist, conf)) {
2492 debug(DBG_ERR, "malloc failed");
2493 list_destroy(conflist);
2496 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2501 void freerealm(struct realm *realm) {
2505 free(realm->message);
2506 regfree(&realm->regex);
2507 pthread_mutex_destroy(&realm->subrealms_mutex);
2508 if (realm->subrealms)
2509 list_destroy(realm->subrealms);
2510 if (realm->srvconfs) {
2511 /* emptying list without freeing data */
2512 while (list_shift(realm->srvconfs));
2513 list_destroy(realm->srvconfs);
2515 if (realm->accsrvconfs) {
2516 /* emptying list without freeing data */
2517 while (list_shift(realm->accsrvconfs));
2518 list_destroy(realm->accsrvconfs);
2523 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2525 struct realm *realm;
2526 char *s, *regex = NULL;
2528 if (*value == '/') {
2529 /* regexp, remove optional trailing / if present */
2530 if (value[strlen(value) - 1] == '/')
2531 value[strlen(value) - 1] = '\0';
2533 /* not a regexp, let us make it one */
2534 if (*value == '*' && !value[1])
2535 regex = stringcopy(".*", 0);
2537 for (n = 0, s = value; *s;)
2540 regex = malloc(strlen(value) + n + 3);
2543 for (n = 1, s = value; *s; s++) {
2553 debug(DBG_ERR, "malloc failed");
2557 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2560 realm = malloc(sizeof(struct realm));
2562 debug(DBG_ERR, "malloc failed");
2565 memset(realm, 0, sizeof(struct realm));
2567 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
2568 debug(DBG_ERR, "mutex init failed");
2574 realm->name = stringcopy(value, 0);
2576 debug(DBG_ERR, "malloc failed");
2579 if (message && strlen(message) > 253) {
2580 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2583 realm->message = message;
2584 realm->accresp = accresp;
2586 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
2587 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2591 if (servers && *servers) {
2592 realm->srvconfs = addsrvconfs(value, servers);
2593 if (!realm->srvconfs)
2597 if (accservers && *accservers) {
2598 realm->accsrvconfs = addsrvconfs(value, accservers);
2599 if (!realm->accsrvconfs)
2603 if (!list_push(realmlist, realm)) {
2604 debug(DBG_ERR, "malloc failed");
2605 pthread_mutex_destroy(&realm->subrealms_mutex);
2609 debug(DBG_DBG, "addrealm: added realm %s", value);
2619 for (n = 0; servers[n]; n++)
2624 for (n = 0; accservers[n]; n++)
2625 free(accservers[n]);
2631 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2632 struct clsrvconf *srvconf;
2633 struct realm *newrealm = NULL;
2634 char *realmname, *s;
2637 if (!conf->dynamiclookupcommand)
2640 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2641 realmname = strrchr(id, '@');
2647 for (s = realmname; *s; s++)
2648 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2651 pthread_mutex_lock(&realm->subrealms_mutex);
2652 /* exit if we now already got a matching subrealm */
2653 if (id2realm(realm->subrealms, id))
2655 srvconf = malloc(sizeof(struct clsrvconf));
2657 debug(DBG_ERR, "malloc failed");
2661 if (!addserver(srvconf))
2664 if (!realm->subrealms)
2665 realm->subrealms = list_create();
2666 if (!realm->subrealms)
2668 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2672 /* add server and accserver to newrealm */
2673 newrealm->srvconfs = list_create();
2674 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2675 debug(DBG_ERR, "malloc failed");
2678 newrealm->accsrvconfs = list_create();
2679 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2680 debug(DBG_ERR, "malloc failed");
2684 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2686 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2687 debug(DBG_ERR, "pthread_create failed");
2690 pthread_detach(clientth);
2695 list_removedata(realm->subrealms, newrealm);
2696 freerealm(newrealm);
2697 if (!list_first(realm->subrealms)) {
2698 list_destroy(realm->subrealms);
2699 realm->subrealms = NULL;
2702 freeserver(srvconf->servers, 1);
2704 debug(DBG_ERR, "failed to create dynamic server");
2707 pthread_mutex_unlock(&realm->subrealms_mutex);
2710 int dynamicconfig(struct server *server) {
2711 int ok, fd[2], status;
2713 struct clsrvconf *conf = server->conf;
2714 struct gconffile *cf = NULL;
2716 /* for now we only learn hostname/address */
2717 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2720 debug(DBG_ERR, "dynamicconfig: pipe error");
2725 debug(DBG_ERR, "dynamicconfig: fork error");
2729 } else if (pid == 0) {
2732 if (fd[1] != STDOUT_FILENO) {
2733 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2734 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2737 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2738 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2742 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2743 ok = getgenericconfig(&cf, NULL,
2744 "Server", CONF_CBK, confserver_cb, (void *)conf,
2749 if (waitpid(pid, &status, 0) < 0) {
2750 debug(DBG_ERR, "dynamicconfig: wait error");
2755 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2763 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2767 int addmatchcertattr(struct clsrvconf *conf) {
2771 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2772 r = &conf->certcnregex;
2773 v = conf->matchcertattr + 4;
2774 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2775 r = &conf->certuriregex;
2776 v = conf->matchcertattr + 20;
2781 /* regexp, remove optional trailing / if present */
2782 if (v[strlen(v) - 1] == '/')
2783 v[strlen(v) - 1] = '\0';
2787 *r = malloc(sizeof(regex_t));
2789 debug(DBG_ERR, "malloc failed");
2792 if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
2795 debug(DBG_ERR, "failed to compile regular expression %s", v);
2801 int addrewriteattr(struct clsrvconf *conf) {
2804 v = conf->rewriteattr + 11;
2805 if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
2807 /* regexp, remove optional trailing / if present */
2808 if (v[strlen(v) - 1] == '/')
2809 v[strlen(v) - 1] = '\0';
2817 conf->rewriteattrregex = malloc(sizeof(regex_t));
2818 if (!conf->rewriteattrregex) {
2819 debug(DBG_ERR, "malloc failed");
2823 conf->rewriteattrreplacement = stringcopy(w, 0);
2824 if (!conf->rewriteattrreplacement) {
2825 free(conf->rewriteattrregex);
2826 conf->rewriteattrregex = NULL;
2830 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
2831 free(conf->rewriteattrregex);
2832 conf->rewriteattrregex = NULL;
2833 free(conf->rewriteattrreplacement);
2834 conf->rewriteattrreplacement = NULL;
2835 debug(DBG_ERR, "failed to compile regular expression %s", v);
2842 /* should accept both names and numeric values, only numeric right now */
2843 uint8_t attrname2val(char *attrname) {
2846 val = atoi(attrname);
2847 return val > 0 && val < 256 ? val : 0;
2850 /* should accept both names and numeric values, only numeric right now */
2851 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2854 *vendor = atoi(attrname);
2855 s = strchr(attrname, ':');
2860 *type = atoi(s + 1);
2861 return *type >= 0 && *type < 256;
2864 struct rewrite *getrewrite(char *alt1, char *alt2) {
2867 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2869 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2874 void addrewrite(char *value, char **attrs, char **vattrs) {
2875 struct rewrite *rewrite = NULL;
2878 uint32_t *p, *va = NULL;
2882 for (; attrs[n]; n++);
2883 a = malloc((n + 1) * sizeof(uint8_t));
2885 debugx(1, DBG_ERR, "malloc failed");
2887 for (i = 0; i < n; i++) {
2888 if (!(a[i] = attrname2val(attrs[i])))
2889 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
2898 for (; vattrs[n]; n++);
2899 va = malloc((2 * n + 1) * sizeof(uint32_t));
2901 debugx(1, DBG_ERR, "malloc failed");
2903 for (p = va, i = 0; i < n; i++, p += 2) {
2904 if (!vattrname2val(vattrs[i], p, p + 1))
2905 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
2913 rewrite = malloc(sizeof(struct rewrite));
2915 debugx(1, DBG_ERR, "malloc failed");
2916 rewrite->removeattrs = a;
2917 rewrite->removevendorattrs = va;
2920 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2921 debugx(1, DBG_ERR, "malloc failed");
2922 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2925 void freeclsrvconf(struct clsrvconf *conf) {
2931 free(conf->matchcertattr);
2932 if (conf->certcnregex)
2933 regfree(conf->certcnregex);
2934 if (conf->certuriregex)
2935 regfree(conf->certuriregex);
2936 free(conf->confrewrite);
2937 free(conf->rewriteattr);
2938 if (conf->rewriteattrregex)
2939 regfree(conf->rewriteattrregex);
2940 free(conf->rewriteattrreplacement);
2941 free(conf->dynamiclookupcommand);
2942 free(conf->rewrite);
2944 freeaddrinfo(conf->addrinfo);
2945 /* not touching ssl_ctx, clients and servers */
2949 int mergeconfstring(char **dst, char **src) {
2958 t = stringcopy(*dst, 0);
2960 debug(DBG_ERR, "malloc failed");
2968 /* assumes dst is a shallow copy */
2969 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2970 if (!mergeconfstring(&dst->name, &src->name) ||
2971 !mergeconfstring(&dst->host, &src->host) ||
2972 !mergeconfstring(&dst->port, &src->port) ||
2973 !mergeconfstring(&dst->secret, &src->secret) ||
2974 !mergeconfstring(&dst->tls, &src->tls) ||
2975 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2976 !mergeconfstring(&dst->confrewrite, &src->confrewrite) ||
2977 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
2980 dst->pdef = src->pdef;
2981 dst->statusserver = src->statusserver;
2982 dst->certnamecheck = src->certnamecheck;
2983 if (src->retryinterval != 255)
2984 dst->retryinterval = src->retryinterval;
2985 if (src->retrycount != 255)
2986 dst->retrycount = src->retrycount;
2990 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2991 struct clsrvconf *conf;
2992 char *conftype = NULL;
2994 debug(DBG_DBG, "confclient_cb called for %s", block);
2996 conf = malloc(sizeof(struct clsrvconf));
2997 if (!conf || !list_push(clconfs, conf))
2998 debugx(1, DBG_ERR, "malloc failed");
2999 memset(conf, 0, sizeof(struct clsrvconf));
3000 conf->certnamecheck = 1;
3002 if (!getgenericconfig(cf, block,
3003 "type", CONF_STR, &conftype,
3004 "host", CONF_STR, &conf->host,
3005 "secret", CONF_STR, &conf->secret,
3006 "tls", CONF_STR, &conf->tls,
3007 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3008 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3009 "rewrite", CONF_STR, &conf->confrewrite,
3010 "rewriteattribute", CONF_STR, &conf->rewriteattr,
3013 debugx(1, DBG_ERR, "configuration error");
3015 conf->name = stringcopy(val, 0);
3017 conf->host = stringcopy(val, 0);
3018 if (!conf->name || !conf->host)
3019 debugx(1, DBG_ERR, "malloc failed");
3022 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3023 conf->type = protoname2int(conftype);
3024 conf->pdef = &protodefs[conf->type];
3025 if (!conf->pdef->name)
3026 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3029 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3030 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultclient", "default");
3032 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3033 if (conf->matchcertattr && !addmatchcertattr(conf))
3034 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3037 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
3039 if (conf->rewriteattr) {
3040 if (!addrewriteattr(conf))
3041 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3044 if (!resolvepeer(conf, 0))
3045 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3047 if (!conf->secret) {
3048 if (!conf->pdef->secretdefault)
3049 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3050 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3052 debugx(1, DBG_ERR, "malloc failed");
3057 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3058 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3059 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultserver", "default");
3060 if (!conf->ssl_ctx) {
3061 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3064 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3065 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3071 conf->port = stringcopy(conf->pdef->portdefault, 0);
3073 debug(DBG_ERR, "malloc failed");
3078 if (conf->retryinterval == 255)
3079 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3080 if (conf->retrycount == 255)
3081 conf->retrycount = protodefs[conf->type].retrycountdefault;
3083 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
3085 if (!conf->secret) {
3086 if (!conf->pdef->secretdefault) {
3087 debug(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);
3091 if (!conf->secret) {
3092 debug(DBG_ERR, "malloc failed");
3097 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3098 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3104 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3105 struct clsrvconf *conf, *resconf;
3106 char *conftype = NULL;
3107 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3109 debug(DBG_DBG, "confserver_cb called for %s", block);
3111 conf = malloc(sizeof(struct clsrvconf));
3113 debug(DBG_ERR, "malloc failed");
3116 memset(conf, 0, sizeof(struct clsrvconf));
3117 resconf = (struct clsrvconf *)arg;
3119 conf->statusserver = resconf->statusserver;
3120 conf->certnamecheck = resconf->certnamecheck;
3122 conf->certnamecheck = 1;
3124 if (!getgenericconfig(cf, block,
3125 "type", CONF_STR, &conftype,
3126 "host", CONF_STR, &conf->host,
3127 "port", CONF_STR, &conf->port,
3128 "secret", CONF_STR, &conf->secret,
3129 "tls", CONF_STR, &conf->tls,
3130 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3131 "rewrite", CONF_STR, &conf->confrewrite,
3132 "StatusServer", CONF_BLN, &conf->statusserver,
3133 "RetryInterval", CONF_LINT, &retryinterval,
3134 "RetryCount", CONF_LINT, &retrycount,
3135 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3136 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3139 debug(DBG_ERR, "configuration error");
3143 conf->name = stringcopy(val, 0);
3145 debug(DBG_ERR, "malloc failed");
3149 conf->host = stringcopy(val, 0);
3151 debug(DBG_ERR, "malloc failed");
3157 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3158 conf->type = protoname2int(conftype);
3159 conf->pdef = &protodefs[conf->type];
3160 if (!conf->pdef->name) {
3161 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3167 if (retryinterval != LONG_MIN) {
3168 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3169 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3172 conf->retryinterval = (uint8_t)retryinterval;
3174 conf->retryinterval = 255;
3176 if (retrycount != LONG_MIN) {
3177 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3178 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3181 conf->retrycount = (uint8_t)retrycount;
3183 conf->retrycount = 255;
3186 if (!mergesrvconf(resconf, conf))
3190 if (conf->dynamiclookupcommand) {
3191 free(conf->dynamiclookupcommand);
3192 conf->dynamiclookupcommand = NULL;
3196 if (resconf || !conf->dynamiclookupcommand) {
3197 if (!compileserverconfig(conf, block))
3204 if (!list_push(srvconfs, conf)) {
3205 debug(DBG_ERR, "malloc failed");
3211 freeclsrvconf(conf);
3215 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3216 char **servers = NULL, **accservers = NULL, *msg = NULL;
3217 uint8_t accresp = 0;
3219 debug(DBG_DBG, "confrealm_cb called for %s", block);
3221 if (!getgenericconfig(cf, block,
3222 "server", CONF_MSTR, &servers,
3223 "accountingServer", CONF_MSTR, &accservers,
3224 "ReplyMessage", CONF_STR, &msg,
3225 "AccountingResponse", CONF_BLN, &accresp,
3228 debugx(1, DBG_ERR, "configuration error");
3230 addrealm(realms, val, servers, accservers, msg, accresp);
3234 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3237 debug(DBG_DBG, "conftls_cb called for %s", block);
3239 conf = malloc(sizeof(struct tls));
3241 debug(DBG_ERR, "conftls_cb: malloc failed");
3244 memset(conf, 0, sizeof(struct tls));
3246 if (!getgenericconfig(cf, block,
3247 "CACertificateFile", CONF_STR, &conf->cacertfile,
3248 "CACertificatePath", CONF_STR, &conf->cacertpath,
3249 "CertificateFile", CONF_STR, &conf->certfile,
3250 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3251 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3252 "CRLCheck", CONF_BLN, &conf->crlcheck,
3255 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3258 if (!conf->certfile || !conf->certkeyfile) {
3259 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3262 if (!conf->cacertfile && !conf->cacertpath) {
3263 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3267 conf->name = stringcopy(val, 0);
3269 debug(DBG_ERR, "conftls_cb: malloc failed");
3273 if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
3274 debug(DBG_ERR, "conftls_cb: malloc failed");
3278 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3282 free(conf->cacertfile);
3283 free(conf->cacertpath);
3284 free(conf->certfile);
3285 free(conf->certkeyfile);
3286 free(conf->certkeypwd);
3291 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3292 char **attrs = NULL, **vattrs = NULL;
3294 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3296 if (!getgenericconfig(cf, block,
3297 "removeAttribute", CONF_MSTR, &attrs,
3298 "removeVendorAttribute", CONF_MSTR, &vattrs,
3301 debugx(1, DBG_ERR, "configuration error");
3302 addrewrite(val, attrs, vattrs);
3306 void getmainconfig(const char *configfile) {
3307 long int loglevel = LONG_MIN;
3308 struct gconffile *cfs;
3310 cfs = openconfigfile(configfile);
3311 memset(&options, 0, sizeof(options));
3313 clconfs = list_create();
3315 debugx(1, DBG_ERR, "malloc failed");
3317 srvconfs = list_create();
3319 debugx(1, DBG_ERR, "malloc failed");
3321 realms = list_create();
3323 debugx(1, DBG_ERR, "malloc failed");
3325 tlsconfs = hash_create();
3327 debugx(1, DBG_ERR, "malloc failed");
3329 rewriteconfs = hash_create();
3331 debugx(1, DBG_ERR, "malloc failed");
3333 if (!getgenericconfig(&cfs, NULL,
3334 "ListenUDP", CONF_MSTR, &options.listenudp,
3335 "ListenTCP", CONF_MSTR, &options.listentcp,
3336 "ListenTLS", CONF_MSTR, &options.listentls,
3337 "ListenDTLS", CONF_MSTR, &options.listendtls,
3338 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
3339 "SourceUDP", CONF_STR, &options.sourceudp,
3340 "SourceTCP", CONF_STR, &options.sourcetcp,
3341 "SourceTLS", CONF_STR, &options.sourcetls,
3342 "SourceDTLS", CONF_STR, &options.sourcedtls,
3343 "LogLevel", CONF_LINT, &loglevel,
3344 "LogDestination", CONF_STR, &options.logdestination,
3345 "LoopPrevention", CONF_BLN, &options.loopprevention,
3346 "Client", CONF_CBK, confclient_cb, NULL,
3347 "Server", CONF_CBK, confserver_cb, NULL,
3348 "Realm", CONF_CBK, confrealm_cb, NULL,
3349 "TLS", CONF_CBK, conftls_cb, NULL,
3350 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3353 debugx(1, DBG_ERR, "configuration error");
3355 if (loglevel != LONG_MIN) {
3356 if (loglevel < 1 || loglevel > 4)
3357 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3358 options.loglevel = (uint8_t)loglevel;
3362 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3365 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3368 *configfile = optarg;
3371 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3372 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3373 *loglevel = *optarg - '0';
3382 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3387 if (!(argc - optind))
3391 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3395 int daemon(int a, int b) {
3403 for (i = 0; i < 3; i++) {
3405 open("/dev/null", O_RDWR);
3411 void *sighandler(void *arg) {
3416 sigemptyset(&sigset);
3417 sigaddset(&sigset, SIGPIPE);
3418 sigwait(&sigset, &sig);
3419 /* only get SIGPIPE right now, so could simplify below code */
3422 /* completely ignoring this */
3425 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3428 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3433 int main(int argc, char **argv) {
3436 struct list_node *entry;
3437 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3438 char *configfile = NULL;
3439 struct clsrvconf *srvconf;
3442 debug_init("radsecproxy");
3443 debug_set_level(DEBUG_LEVEL);
3445 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3447 debug_set_level(loglevel);
3448 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3450 options.loglevel = loglevel;
3451 else if (options.loglevel)
3452 debug_set_level(options.loglevel);
3454 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3455 free(options.logdestination);
3457 if (!list_first(clconfs))
3458 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3459 if (!list_first(realms))
3460 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3463 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3465 if (!foreground && (daemon(0, 0) < 0))
3466 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3468 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3470 sigemptyset(&sigset);
3471 /* exit on all but SIGPIPE, ignore more? */
3472 sigaddset(&sigset, SIGPIPE);
3473 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3474 pthread_create(&sigth, NULL, sighandler, NULL);
3476 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3477 srvconf = (struct clsrvconf *)entry->data;
3478 if (srvconf->dynamiclookupcommand)
3480 if (!addserver(srvconf))
3481 debugx(1, DBG_ERR, "failed to add server");
3482 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3483 (void *)(srvconf->servers)))
3484 debugx(1, DBG_ERR, "pthread_create failed");
3486 /* srcprotores for UDP no longer needed */
3487 if (srcprotores[RAD_UDP]) {
3488 freeaddrinfo(srcprotores[RAD_UDP]);
3489 srcprotores[RAD_UDP] = NULL;
3492 for (i = 0; protodefs[i].name; i++)
3493 if (protodefs[i].initextra)
3494 protodefs[i].initextra();
3496 if (find_clconf_type(RAD_TCP, NULL))
3497 createlisteners(RAD_TCP, options.listentcp);
3499 if (find_clconf_type(RAD_TLS, NULL))
3500 createlisteners(RAD_TLS, options.listentls);
3502 if (find_clconf_type(RAD_DTLS, NULL))
3503 createlisteners(RAD_DTLS, options.listendtls);
3505 if (find_clconf_type(RAD_UDP, NULL)) {
3506 createlisteners(RAD_UDP, options.listenudp);
3507 if (options.listenaccudp)
3508 createlisteners(RAD_UDP, options.listenaccudp);
3511 /* just hang around doing nothing, anything to do here? */