2 * Copyright (C) 2006-2008 Stig Venaas <venaas@uninett.no>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
9 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
10 * rd is responsible for init and launching wr
11 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
12 * each tlsserverrd launches tlsserverwr
13 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
14 * for init and launching rd
16 * serverrd will receive a request, processes it and puts it in the requestq of
17 * the appropriate clientwr
18 * clientwr monitors its requestq and sends requests
19 * clientrd looks for responses, processes them and puts them in the replyq of
20 * the peer the request came from
21 * serverwr monitors its reply and sends replies
23 * In addition to the main thread, we have:
24 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
25 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
26 * For each TLS peer connecting to us there will be 2 more TLS threads
27 * This is only for connected peers
28 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
29 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
33 * TCP accounting not yet supported
34 * We are not removing client requests from dynamic servers, see removeclientrqs()
38 #include <sys/socket.h>
39 #include <netinet/in.h>
48 #include <sys/types.h>
49 #include <sys/select.h>
52 #include <arpa/inet.h>
56 #include <openssl/ssl.h>
57 #include <openssl/rand.h>
58 #include <openssl/err.h>
59 #include <openssl/md5.h>
60 #include <openssl/hmac.h>
61 #include <openssl/x509v3.h>
67 #include "radsecproxy.h"
73 static struct options options;
74 static struct list *clconfs, *srvconfs;
76 struct hash *tlsconfs, *rewriteconfs;
78 static struct addrinfo *srcprotores[4] = { NULL, NULL, NULL, NULL };
80 static pthread_mutex_t *ssl_locks = NULL;
81 static long *ssl_lock_count;
85 /* minimum required declarations to avoid reordering code */
86 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
87 int dynamicconfig(struct server *server);
88 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
89 void freerealm(struct realm *realm);
90 void freeclsrvconf(struct clsrvconf *conf);
91 void freerqdata(struct request *rq);
93 static const struct protodefs protodefs[] = {
94 { "udp", /* UDP, assuming RAD_UDP defined as 0 */
95 NULL, /* secretdefault */
96 SOCK_DGRAM, /* socktype */
97 "1812", /* portdefault */
98 REQUEST_RETRY_COUNT, /* retrycountdefault */
99 10, /* retrycountmax */
100 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
101 60, /* retryintervalmax */
102 udpserverrd, /* listener */
103 &options.sourceudp, /* srcaddrport */
104 NULL, /* connecter */
105 NULL, /* clientconnreader */
106 clientradputudp, /* clientradput */
107 addclientudp, /* addclient */
108 addserverextraudp, /* addserverextra */
109 initextraudp /* initextra */
111 { "tls", /* TLS, assuming RAD_TLS defined as 1 */
112 "mysecret", /* secretdefault */
113 SOCK_STREAM, /* socktype */
114 "2083", /* portdefault */
115 0, /* retrycountdefault */
116 0, /* retrycountmax */
117 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
118 60, /* retryintervalmax */
119 tlslistener, /* listener */
120 &options.sourcetls, /* srcaddrport */
121 tlsconnect, /* connecter */
122 tlsclientrd, /* clientconnreader */
123 clientradputtls, /* clientradput */
124 NULL, /* addclient */
125 NULL, /* addserverextra */
128 { "tcp", /* TCP, assuming RAD_TCP defined as 2 */
129 NULL, /* secretdefault */
130 SOCK_STREAM, /* socktype */
131 "1812", /* portdefault */
132 0, /* retrycountdefault */
133 0, /* retrycountmax */
134 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
135 60, /* retryintervalmax */
136 tcplistener, /* listener */
137 &options.sourcetcp, /* srcaddrport */
138 tcpconnect, /* connecter */
139 tcpclientrd, /* clientconnreader */
140 clientradputtcp, /* clientradput */
141 NULL, /* addclient */
142 NULL, /* addserverextra */
145 { "dtls", /* DTLS, assuming RAD_DTLS defined as 3 */
146 "mysecret", /* secretdefault */
147 SOCK_DGRAM, /* socktype */
148 "2083", /* portdefault */
149 REQUEST_RETRY_COUNT, /* retrycountdefault */
150 10, /* retrycountmax */
151 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
152 60, /* retryintervalmax */
153 udpdtlsserverrd, /* listener */
154 &options.sourcedtls, /* srcaddrport */
155 dtlsconnect, /* connecter */
156 dtlsclientrd, /* clientconnreader */
157 clientradputdtls, /* clientradput */
158 NULL, /* addclient */
159 addserverextradtls, /* addserverextra */
160 initextradtls /* initextra */
166 uint8_t protoname2int(const char *name) {
169 for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
173 /* callbacks for making OpenSSL thread safe */
174 unsigned long ssl_thread_id() {
175 return (unsigned long)pthread_self();
178 void ssl_locking_callback(int mode, int type, const char *file, int line) {
179 if (mode & CRYPTO_LOCK) {
180 pthread_mutex_lock(&ssl_locks[type]);
181 ssl_lock_count[type]++;
183 pthread_mutex_unlock(&ssl_locks[type]);
186 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
187 int pwdlen = strlen(userdata);
188 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
190 memcpy(buf, userdata, pwdlen);
194 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
199 err_cert = X509_STORE_CTX_get_current_cert(ctx);
200 err = X509_STORE_CTX_get_error(ctx);
201 depth = X509_STORE_CTX_get_error_depth(ctx);
203 if (depth > MAX_CERT_DEPTH) {
205 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
206 X509_STORE_CTX_set_error(ctx, err);
210 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
211 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
214 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
215 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
216 debug(DBG_WARN, "\tIssuer=%s", buf);
218 case X509_V_ERR_CERT_NOT_YET_VALID:
219 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
220 debug(DBG_WARN, "\tCertificate not yet valid");
222 case X509_V_ERR_CERT_HAS_EXPIRED:
223 debug(DBG_WARN, "Certificate has expired");
225 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
226 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
231 printf("certificate verify returns %d\n", ok);
236 struct addrinfo *getsrcprotores(uint8_t type) {
237 return srcprotores[type];
240 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
241 struct addrinfo hints, *addrinfo, *res;
245 slash = conf->host ? strchr(conf->host, '/') : NULL;
249 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
253 if (*s < '0' || *s > '9') {
254 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
257 plen = atoi(slash + 1);
258 if (plen < 0 || plen > 128) {
259 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
264 memset(&hints, 0, sizeof(hints));
265 hints.ai_socktype = conf->pdef->socktype;
266 hints.ai_family = AF_UNSPEC;
267 hints.ai_flags = ai_flags;
268 if (!conf->host && !conf->port) {
269 /* getaddrinfo() doesn't like host and port to be NULL */
270 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
271 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
274 for (res = addrinfo; res; res = res->ai_next) {
275 switch (res->ai_family) {
277 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
280 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
286 hints.ai_flags |= AI_NUMERICHOST;
287 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
288 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
293 switch (addrinfo->ai_family) {
296 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
297 freeaddrinfo(addrinfo);
304 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
305 freeaddrinfo(addrinfo);
308 conf->prefixlen = plen;
310 conf->prefixlen = 255;
313 freeaddrinfo(conf->addrinfo);
314 conf->addrinfo = addrinfo;
318 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
323 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
327 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
329 debugx(1, DBG_ERR, "no ] matching initial [");
333 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
336 debugx(1, DBG_ERR, "missing host/address");
338 conf->host = stringcopy(field, p - field);
341 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
342 debugx(1, DBG_ERR, "unexpected character after ]");
345 /* port number or service name is specified */;
347 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
349 debugx(1, DBG_ERR, "syntax error, : but no following port");
350 conf->port = stringcopy(field, p - field);
352 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
356 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
357 struct clsrvconf *conf;
359 conf = malloc(sizeof(struct clsrvconf));
361 debugx(1, DBG_ERR, "malloc failed");
362 memset(conf, 0, sizeof(struct clsrvconf));
364 conf->pdef = &protodefs[conf->type];
366 parsehostport(lconf, conf, default_port);
367 if (!strcmp(conf->host, "*")) {
372 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
373 if (!resolvepeer(conf, AI_PASSIVE))
374 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
378 void freeclsrvres(struct clsrvconf *res) {
382 freeaddrinfo(res->addrinfo);
386 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
388 struct addrinfo *res;
390 for (res = addrinfo; res; res = res->ai_next) {
391 if (family != AF_UNSPEC && family != res->ai_family)
393 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
395 debug(DBG_WARN, "bindtoaddr: socket failed");
399 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
402 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
404 if (!bind(s, res->ai_addr, res->ai_addrlen))
406 debug(DBG_WARN, "bindtoaddr: bind failed");
412 int connecttcp(struct addrinfo *addrinfo, struct addrinfo *src) {
414 struct addrinfo *res;
417 for (res = addrinfo; res; res = res->ai_next) {
418 s = bindtoaddr(src, res->ai_family, 1, 1);
420 debug(DBG_WARN, "connecttoserver: socket failed");
423 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
425 debug(DBG_WARN, "connecttoserver: connect failed");
432 /* returns 1 if the len first bits are equal, else 0 */
433 int prefixmatch(void *a1, void *a2, uint8_t len) {
434 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
436 if (l && memcmp(a1, a2, l))
441 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
444 /* returns next config with matching address, or NULL */
445 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
446 struct sockaddr_in6 *sa6 = NULL;
447 struct in_addr *a4 = NULL;
448 struct addrinfo *res;
449 struct list_node *entry;
450 struct clsrvconf *conf;
452 if (addr->sa_family == AF_INET6) {
453 sa6 = (struct sockaddr_in6 *)addr;
454 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
455 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
459 a4 = &((struct sockaddr_in *)addr)->sin_addr;
461 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
462 conf = (struct clsrvconf *)entry->data;
463 if (conf->type == type) {
464 if (conf->prefixlen == 255) {
465 for (res = conf->addrinfo; res; res = res->ai_next)
466 if ((a4 && res->ai_family == AF_INET &&
467 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
468 (sa6 && res->ai_family == AF_INET6 &&
469 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
475 res = conf->addrinfo;
477 ((a4 && res->ai_family == AF_INET &&
478 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
479 (sa6 && res->ai_family == AF_INET6 &&
480 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
491 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
492 return find_conf(type, addr, clconfs, cur);
495 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
496 return find_conf(type, addr, srvconfs, cur);
499 /* returns next config of given type, or NULL */
500 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
501 struct list_node *entry;
502 struct clsrvconf *conf;
504 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
505 conf = (struct clsrvconf *)entry->data;
506 if (conf->type == type) {
515 struct queue *newqueue() {
518 q = malloc(sizeof(struct queue));
520 debugx(1, DBG_ERR, "malloc failed");
521 q->entries = list_create();
523 debugx(1, DBG_ERR, "malloc failed");
524 pthread_mutex_init(&q->mutex, NULL);
525 pthread_cond_init(&q->cond, NULL);
529 void removequeue(struct queue *q) {
530 struct list_node *entry;
534 pthread_mutex_lock(&q->mutex);
535 for (entry = list_first(q->entries); entry; entry = list_next(entry))
536 free(((struct reply *)entry)->buf);
537 list_destroy(q->entries);
538 pthread_cond_destroy(&q->cond);
539 pthread_mutex_unlock(&q->mutex);
540 pthread_mutex_destroy(&q->mutex);
544 void freebios(struct queue *q) {
547 pthread_mutex_lock(&q->mutex);
548 while ((bio = (BIO *)list_shift(q->entries)))
550 pthread_mutex_unlock(&q->mutex);
554 struct client *addclient(struct clsrvconf *conf) {
555 struct client *new = malloc(sizeof(struct client));
558 debug(DBG_ERR, "malloc failed");
561 if (!conf->clients) {
562 conf->clients = list_create();
563 if (!conf->clients) {
564 debug(DBG_ERR, "malloc failed");
569 memset(new, 0, sizeof(struct client));
571 if (conf->pdef->addclient)
572 conf->pdef->addclient(new);
574 new->replyq = newqueue();
575 list_push(conf->clients, new);
579 void removeclient(struct client *client) {
580 if (!client || !client->conf->clients)
582 removequeue(client->replyq);
583 list_removedata(client->conf->clients, client);
587 void removeclientrqs(struct client *client) {
588 struct list_node *entry;
589 struct server *server;
593 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
594 server = ((struct clsrvconf *)entry->data)->servers;
597 pthread_mutex_lock(&server->newrq_mutex);
598 for (i = 0; i < MAX_REQUESTS; i++) {
599 rq = server->requests + i;
600 if (rq->from == client)
603 pthread_mutex_unlock(&server->newrq_mutex);
607 void freeserver(struct server *server, uint8_t destroymutex) {
608 struct request *rq, *end;
613 if (server->requests) {
614 rq = server->requests;
615 for (end = rq + MAX_REQUESTS; rq < end; rq++)
617 free(server->requests);
620 freebios(server->rbios);
621 free(server->dynamiclookuparg);
623 pthread_mutex_destroy(&server->lock);
624 pthread_cond_destroy(&server->newrq_cond);
625 pthread_mutex_destroy(&server->newrq_mutex);
630 int addserver(struct clsrvconf *conf) {
631 struct clsrvconf *res;
635 debug(DBG_ERR, "addserver: currently works with just one server per conf");
638 conf->servers = malloc(sizeof(struct server));
639 if (!conf->servers) {
640 debug(DBG_ERR, "malloc failed");
643 memset(conf->servers, 0, sizeof(struct server));
644 conf->servers->conf = conf;
647 if (type == RAD_DTLS)
648 conf->servers->rbios = newqueue();
650 if (!srcprotores[type]) {
651 res = resolve_hostport(type, *conf->pdef->srcaddrport, NULL);
652 srcprotores[type] = res->addrinfo;
653 res->addrinfo = NULL;
657 conf->servers->sock = -1;
658 if (conf->pdef->addserverextra)
659 conf->pdef->addserverextra(conf);
661 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
662 if (!conf->servers->requests) {
663 debug(DBG_ERR, "malloc failed");
666 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
667 debug(DBG_ERR, "mutex init failed");
670 conf->servers->newrq = 0;
671 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
672 debug(DBG_ERR, "mutex init failed");
673 pthread_mutex_destroy(&conf->servers->lock);
676 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
677 debug(DBG_ERR, "mutex init failed");
678 pthread_mutex_destroy(&conf->servers->newrq_mutex);
679 pthread_mutex_destroy(&conf->servers->lock);
686 freeserver(conf->servers, 0);
687 conf->servers = NULL;
691 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
692 int loc, i, l, n, r = 0;
695 STACK_OF(GENERAL_NAME) *alt;
698 debug(DBG_DBG, "subjectaltnameaddr");
700 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
704 ex = X509_get_ext(cert, loc);
705 alt = X509V3_EXT_d2i(ex);
709 n = sk_GENERAL_NAME_num(alt);
710 for (i = 0; i < n; i++) {
711 gn = sk_GENERAL_NAME_value(alt, i);
712 if (gn->type != GEN_IPADD)
715 v = (char *)ASN1_STRING_data(gn->d.ia5);
716 l = ASN1_STRING_length(gn->d.ia5);
717 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
718 && !memcmp(v, &addr, l)) {
723 GENERAL_NAMES_free(alt);
727 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
734 nm = X509_get_subject_name(cert);
737 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
740 e = X509_NAME_get_entry(nm, loc);
741 t = X509_NAME_ENTRY_get_data(e);
742 v = (char *) ASN1_STRING_data(t);
743 l = ASN1_STRING_length(t);
747 if (l == strlen(exact) && !strncasecmp(exact, v, l))
750 s = stringcopy((char *)v, l);
752 debug(DBG_ERR, "malloc failed");
755 if (regexec(regex, s, 0, NULL, 0)) {
766 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
767 int loc, i, l, n, r = 0;
770 STACK_OF(GENERAL_NAME) *alt;
773 debug(DBG_DBG, "subjectaltnameregexp");
775 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
779 ex = X509_get_ext(cert, loc);
780 alt = X509V3_EXT_d2i(ex);
784 n = sk_GENERAL_NAME_num(alt);
785 for (i = 0; i < n; i++) {
786 gn = sk_GENERAL_NAME_value(alt, i);
787 if (gn->type != type)
790 v = (char *)ASN1_STRING_data(gn->d.ia5);
791 l = ASN1_STRING_length(gn->d.ia5);
795 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
798 if (memcmp(v, exact, l))
801 s = stringcopy((char *)v, l);
803 debug(DBG_ERR, "malloc failed");
806 if (regexec(regex, s, 0, NULL, 0)) {
815 GENERAL_NAMES_free(alt);
819 X509 *verifytlscert(SSL *ssl) {
823 if (SSL_get_verify_result(ssl) != X509_V_OK) {
824 debug(DBG_ERR, "verifytlscert: basic validation failed");
825 while ((error = ERR_get_error()))
826 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
830 cert = SSL_get_peer_certificate(ssl);
832 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
836 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
838 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
839 struct in6_addr addr;
841 if (conf->certnamecheck && conf->prefixlen == 255) {
842 if (inet_pton(AF_INET, conf->host, &addr))
844 else if (inet_pton(AF_INET6, conf->host, &addr))
847 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
850 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
853 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
855 if (!cnregexp(cert, conf->host, NULL)) {
856 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
859 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
862 if (conf->certcnregex) {
863 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
864 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
867 debug(DBG_DBG, "verifyconfcert: CN matching regex");
869 if (conf->certuriregex) {
870 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
871 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
874 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
879 int radsign(unsigned char *rad, unsigned char *sec) {
880 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
881 static unsigned char first = 1;
882 static EVP_MD_CTX mdctx;
886 pthread_mutex_lock(&lock);
888 EVP_MD_CTX_init(&mdctx);
892 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
893 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
894 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
895 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
897 pthread_mutex_unlock(&lock);
901 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
902 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
903 static unsigned char first = 1;
904 static EVP_MD_CTX mdctx;
905 unsigned char hash[EVP_MAX_MD_SIZE];
909 pthread_mutex_lock(&lock);
911 EVP_MD_CTX_init(&mdctx);
917 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
918 EVP_DigestUpdate(&mdctx, rad, 4) &&
919 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
920 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
921 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
922 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
924 !memcmp(hash, rad + 4, 16));
925 pthread_mutex_unlock(&lock);
929 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
930 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
931 static unsigned char first = 1;
932 static HMAC_CTX hmacctx;
934 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
936 pthread_mutex_lock(&lock);
938 HMAC_CTX_init(&hmacctx);
942 memcpy(auth, authattr, 16);
943 memset(authattr, 0, 16);
945 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
946 HMAC_Update(&hmacctx, rad, RADLEN(rad));
947 HMAC_Final(&hmacctx, hash, &md_len);
948 memcpy(authattr, auth, 16);
950 debug(DBG_WARN, "message auth computation failed");
951 pthread_mutex_unlock(&lock);
955 if (memcmp(auth, hash, 16)) {
956 debug(DBG_WARN, "message authenticator, wrong value");
957 pthread_mutex_unlock(&lock);
961 pthread_mutex_unlock(&lock);
965 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
966 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
967 static unsigned char first = 1;
968 static HMAC_CTX hmacctx;
974 pthread_mutex_lock(&lock);
976 HMAC_CTX_init(&hmacctx);
980 memset(authattrval, 0, 16);
982 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
983 HMAC_Update(&hmacctx, rad, RADLEN(rad));
984 HMAC_Final(&hmacctx, authattrval, &md_len);
986 debug(DBG_WARN, "message auth computation failed");
987 pthread_mutex_unlock(&lock);
991 pthread_mutex_unlock(&lock);
995 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
997 if (ATTRTYPE(attrs) == type)
999 length -= ATTRLEN(attrs);
1000 attrs += ATTRLEN(attrs);
1005 void freerqdata(struct request *rq) {
1006 if (rq->origusername)
1007 free(rq->origusername);
1012 void sendrq(struct server *to, struct request *rq) {
1016 pthread_mutex_lock(&to->newrq_mutex);
1017 /* might simplify if only try nextid, might be ok */
1018 for (i = to->nextid; i < MAX_REQUESTS; i++)
1019 if (!to->requests[i].buf)
1021 if (i == MAX_REQUESTS) {
1022 for (i = 0; i < to->nextid; i++)
1023 if (!to->requests[i].buf)
1025 if (i == to->nextid) {
1026 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
1032 rq->buf[1] = (char)i;
1034 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1035 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1040 if (*rq->buf == RAD_Accounting_Request) {
1041 if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
1042 debug(DBG_WARN, "sendrq: failed to sign Accounting-Request message");
1048 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1049 to->requests[i] = *rq;
1054 debug(DBG_DBG, "sendrq: signalling client writer");
1055 pthread_cond_signal(&to->newrq_cond);
1058 pthread_mutex_unlock(&to->newrq_mutex);
1061 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa, int toudpsock) {
1062 struct reply *reply;
1065 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1067 debug(DBG_WARN, "sendreply: failed to sign message");
1071 reply = malloc(sizeof(struct reply));
1074 debug(DBG_ERR, "sendreply: malloc failed");
1077 memset(reply, 0, sizeof(struct reply));
1080 reply->tosa = *tosa;
1081 reply->toudpsock = toudpsock;
1083 pthread_mutex_lock(&to->replyq->mutex);
1085 first = list_first(to->replyq->entries) == NULL;
1087 if (!list_push(to->replyq->entries, reply)) {
1088 pthread_mutex_unlock(&to->replyq->mutex);
1091 debug(DBG_ERR, "sendreply: malloc failed");
1096 debug(DBG_DBG, "signalling server writer");
1097 pthread_cond_signal(&to->replyq->cond);
1099 pthread_mutex_unlock(&to->replyq->mutex);
1102 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1103 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1104 static unsigned char first = 1;
1105 static EVP_MD_CTX mdctx;
1106 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1107 unsigned int md_len;
1108 uint8_t i, offset = 0, out[128];
1110 pthread_mutex_lock(&lock);
1112 EVP_MD_CTX_init(&mdctx);
1118 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1119 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1120 !EVP_DigestUpdate(&mdctx, input, 16) ||
1121 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1123 pthread_mutex_unlock(&lock);
1126 for (i = 0; i < 16; i++)
1127 out[offset + i] = hash[i] ^ in[offset + i];
1128 input = out + offset - 16;
1133 memcpy(in, out, len);
1134 pthread_mutex_unlock(&lock);
1138 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1139 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1140 static unsigned char first = 1;
1141 static EVP_MD_CTX mdctx;
1142 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1143 unsigned int md_len;
1144 uint8_t i, offset = 0, out[128];
1146 pthread_mutex_lock(&lock);
1148 EVP_MD_CTX_init(&mdctx);
1154 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1155 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1156 !EVP_DigestUpdate(&mdctx, input, 16) ||
1157 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1159 pthread_mutex_unlock(&lock);
1162 for (i = 0; i < 16; i++)
1163 out[offset + i] = hash[i] ^ in[offset + i];
1164 input = in + offset;
1169 memcpy(in, out, len);
1170 pthread_mutex_unlock(&lock);
1174 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1175 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1176 static unsigned char first = 1;
1177 static EVP_MD_CTX mdctx;
1178 unsigned char hash[EVP_MAX_MD_SIZE];
1179 unsigned int md_len;
1182 pthread_mutex_lock(&lock);
1184 EVP_MD_CTX_init(&mdctx);
1189 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1190 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1191 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1194 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1195 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1196 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1197 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1198 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1199 pthread_mutex_unlock(&lock);
1204 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1207 for (i = 0; i < 16; i++)
1210 for (offset = 16; offset < len; offset += 16) {
1212 printf("text + offset - 16 c(%d): ", offset / 16);
1213 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1215 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1216 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1217 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1218 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1220 pthread_mutex_unlock(&lock);
1224 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1227 for (i = 0; i < 16; i++)
1228 text[offset + i] ^= hash[i];
1232 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1235 pthread_mutex_unlock(&lock);
1239 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1240 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1241 static unsigned char first = 1;
1242 static EVP_MD_CTX mdctx;
1243 unsigned char hash[EVP_MAX_MD_SIZE];
1244 unsigned int md_len;
1248 pthread_mutex_lock(&lock);
1250 EVP_MD_CTX_init(&mdctx);
1255 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1256 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1257 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1260 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1261 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1262 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1263 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1264 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1265 pthread_mutex_unlock(&lock);
1270 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1273 for (i = 0; i < 16; i++)
1274 plain[i] = text[i] ^ hash[i];
1276 for (offset = 16; offset < len; offset += 16) {
1278 printf("text + offset - 16 c(%d): ", offset / 16);
1279 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1281 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1282 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1283 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1284 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1286 pthread_mutex_unlock(&lock);
1290 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1293 for (i = 0; i < 16; i++)
1294 plain[offset + i] = text[offset + i] ^ hash[i];
1297 memcpy(text, plain, len);
1299 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1302 pthread_mutex_unlock(&lock);
1306 struct realm *id2realm(struct list *realmlist, char *id) {
1307 struct list_node *entry;
1308 struct realm *realm, *subrealm = NULL;
1310 /* need to do locking for subrealms and check subrealm timers */
1311 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1312 realm = (struct realm *)entry->data;
1313 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1314 pthread_mutex_lock(&realm->subrealms_mutex);
1315 if (realm->subrealms)
1316 subrealm = id2realm(realm->subrealms, id);
1317 pthread_mutex_unlock(&realm->subrealms_mutex);
1318 return subrealm ? subrealm : realm;
1324 /* helper function, only used by removeserversubrealms() */
1325 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1326 struct list_node *entry;
1327 struct realm *realm;
1329 for (entry = list_first(realmlist); entry;) {
1330 realm = (struct realm *)entry->data;
1331 entry = list_next(entry);
1332 if (realm->srvconfs) {
1333 list_removedata(realm->srvconfs, srv);
1334 if (!list_first(realm->srvconfs)) {
1335 list_destroy(realm->srvconfs);
1336 realm->srvconfs = NULL;
1339 if (realm->accsrvconfs) {
1340 list_removedata(realm->accsrvconfs, srv);
1341 if (!list_first(realm->accsrvconfs)) {
1342 list_destroy(realm->accsrvconfs);
1343 realm->accsrvconfs = NULL;
1347 /* remove subrealm if no servers */
1348 if (!realm->srvconfs && !realm->accsrvconfs) {
1349 list_removedata(realmlist, realm);
1355 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1356 struct list_node *entry;
1357 struct realm *realm;
1359 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1360 realm = (struct realm *)entry->data;
1361 pthread_mutex_lock(&realm->subrealms_mutex);
1362 if (realm->subrealms) {
1363 _internal_removeserversubrealms(realm->subrealms, srv);
1364 if (!list_first(realm->subrealms)) {
1365 list_destroy(realm->subrealms);
1366 realm->subrealms = NULL;
1369 pthread_mutex_unlock(&realm->subrealms_mutex);
1373 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1374 struct request *rq = to->requests, *end;
1376 pthread_mutex_lock(&to->newrq_mutex);
1377 for (end = rq + MAX_REQUESTS; rq < end; rq++)
1378 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1380 pthread_mutex_unlock(&to->newrq_mutex);
1385 int attrvalidate(unsigned char *attrs, int length) {
1386 while (length > 1) {
1387 if (ATTRLEN(attrs) < 2) {
1388 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1391 length -= ATTRLEN(attrs);
1393 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1396 attrs += ATTRLEN(attrs);
1399 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1403 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1404 if (len < 16 || len > 128 || len % 16) {
1405 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1409 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1410 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1414 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1416 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1417 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1423 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1426 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1427 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1430 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1431 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1437 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1438 char *oldsecret, char *newsecret) {
1439 unsigned char *attr;
1441 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1442 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1443 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1449 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1453 for (; attrs[0]; attrs += 2)
1454 if (attrs[0] == vendor && attrs[1] == subattr)
1459 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1460 uint8_t alen, sublen, rmlen = 0;
1461 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1464 if (!removevendorattrs)
1467 while (*removevendorattrs && *removevendorattrs != vendor)
1468 removevendorattrs += 2;
1469 if (!*removevendorattrs)
1472 alen = ATTRLEN(attrs);
1474 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1475 /* remove entire vendor attribute */
1476 memmove(attrs, attrs + alen, length - alen);
1481 subattrs = ATTRVAL(attrs) + 4;
1483 if (!attrvalidate(subattrs, sublen)) {
1484 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1489 while (sublen > 1) {
1490 alen = ATTRLEN(subattrs);
1493 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1494 memmove(subattrs, subattrs + alen, length);
1500 ATTRLEN(attrs) -= rmlen;
1504 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1505 uint8_t *attrs, alen;
1506 uint16_t len, rmlen = 0;
1508 if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1511 len = RADLEN(buf) - 20;
1514 alen = ATTRLEN(attrs);
1516 if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1517 memmove(attrs, attrs + alen, len);
1519 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1520 rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1525 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1528 /* returns a pointer to the resized attribute value */
1529 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1530 uint8_t *attrs, *attr, vallen;
1534 len = RADLEN(*buf) - 20;
1537 attr = attrget(attrs, len, type);
1541 vallen = ATTRVALLEN(attr);
1542 if (vallen == newvallen)
1545 len += newvallen - vallen;
1546 if (newvallen > vallen) {
1547 new = realloc(*buf, len + 20);
1549 debug(DBG_ERR, "resizeattr: malloc failed");
1558 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1559 attr[1] = newvallen + 2;
1560 ((uint16_t *)*buf)[1] = htons(len + 20);
1564 int rewriteusername(struct request *rq, char *in) {
1565 size_t nmatch = 10, reslen = 0, start = 0;
1566 regmatch_t pmatch[10], *pfield;
1568 unsigned char *result;
1569 char *out = rq->from->conf->rewriteattrreplacement;
1571 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1572 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1576 rq->origusername = stringcopy(in, 0);
1577 if (!rq->origusername)
1580 for (i = start; out[i]; i++) {
1581 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1582 pfield = &pmatch[out[i + 1] - '0'];
1583 if (pfield->rm_so >= 0) {
1584 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1590 reslen += i - start;
1592 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1598 for (i = start; out[i]; i++) {
1599 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1600 pfield = &pmatch[out[i + 1] - '0'];
1601 if (pfield->rm_so >= 0) {
1602 memcpy(result + reslen, out + start, i - start);
1603 reslen += i - start;
1604 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1605 reslen += pfield->rm_eo - pfield->rm_so;
1612 memcpy(result + reslen, out + start, i - start);
1613 reslen += i - start;
1614 memcpy(in, result, reslen);
1619 const char *radmsgtype2string(uint8_t code) {
1620 static const char *rad_msg_names[] = {
1621 "", "Access-Request", "Access-Accept", "Access-Reject",
1622 "Accounting-Request", "Accounting-Response", "", "",
1623 "", "", "", "Access-Challenge",
1624 "Status-Server", "Status-Client"
1626 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1629 void char2hex(char *h, unsigned char c) {
1630 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1631 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1632 h[0] = hexdigits[c / 16];
1633 h[1] = hexdigits[c % 16];
1637 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
1641 if (!attr || len == 1) {
1646 l = ATTRVALLEN(attr);
1647 s = (char *)ATTRVAL(attr);
1650 for (i = 0; i < l; i++) {
1651 if (s[i] > 31 && s[i] < 127) {
1653 if (d - ascii == len - 1)
1656 if (d - ascii > len - 4)
1661 if (d - ascii == len - 1)
1669 void acclog(unsigned char *attrs, int length, char *host) {
1670 unsigned char *attr;
1673 attr = attrget(attrs, length, RAD_Attr_User_Name);
1675 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1678 radattr2ascii(username, sizeof(username), attr);
1679 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1682 void respondaccounting(struct request *rq) {
1683 unsigned char *resp;
1687 debug(DBG_ERR, "respondaccounting: malloc failed");
1690 memcpy(resp, rq->buf, 20);
1691 resp[0] = RAD_Accounting_Response;
1694 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1695 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1698 void respondstatusserver(struct request *rq) {
1699 unsigned char *resp;
1703 debug(DBG_ERR, "respondstatusserver: malloc failed");
1706 memcpy(resp, rq->buf, 20);
1707 resp[0] = RAD_Access_Accept;
1710 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1711 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1714 void respondreject(struct request *rq, char *message) {
1715 unsigned char *resp;
1718 if (message && *message)
1719 len += 2 + strlen(message);
1723 debug(DBG_ERR, "respondreject: malloc failed");
1726 memcpy(resp, rq->buf, 20);
1727 resp[0] = RAD_Access_Reject;
1728 *(uint16_t *)(resp + 2) = htons(len);
1729 if (message && *message) {
1730 resp[20] = RAD_Attr_Reply_Message;
1731 resp[21] = len - 20;
1732 memcpy(resp + 22, message, len - 22);
1734 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1737 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1738 struct list_node *entry;
1739 struct clsrvconf *server, *best = NULL, *first = NULL;
1741 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1742 server = (struct clsrvconf *)entry->data;
1743 if (!server->servers)
1747 if (!server->servers->connectionok)
1749 if (!server->servers->lostrqs)
1755 if (server->servers->lostrqs < best->servers->lostrqs)
1758 return best ? best : first;
1761 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
1762 struct clsrvconf *srvconf;
1764 *realm = id2realm(realms, id);
1767 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1768 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1771 if (!acc && !srvconf->servers)
1772 adddynamicrealmserver(*realm, srvconf, id);
1773 return srvconf->servers;
1776 /* returns 0 if validation/authentication fails, else 1 */
1777 int radsrv(struct request *rq) {
1778 uint8_t code, id, *auth, *attrs, *attr;
1780 struct server *to = NULL;
1781 char username[254], userascii[760];
1782 unsigned char newauth[16];
1783 struct realm *realm = NULL;
1785 code = *(uint8_t *)rq->buf;
1786 id = *(uint8_t *)(rq->buf + 1);
1787 len = RADLEN(rq->buf);
1788 auth = (uint8_t *)(rq->buf + 4);
1790 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1792 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1793 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1798 attrs = rq->buf + 20;
1800 if (!attrvalidate(attrs, len)) {
1801 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1805 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1806 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
1807 debug(DBG_WARN, "radsrv: message authentication failed");
1811 if (code == RAD_Status_Server) {
1812 respondstatusserver(rq);
1816 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1818 if (code == RAD_Accounting_Request) {
1819 memset(newauth, 0, 16);
1820 if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
1821 debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
1826 if (rq->from->conf->rewrite) {
1827 dorewrite(rq->buf, rq->from->conf->rewrite);
1828 len = RADLEN(rq->buf) - 20;
1831 attr = attrget(attrs, len, RAD_Attr_User_Name);
1833 if (code == RAD_Accounting_Request) {
1834 acclog(attrs, len, rq->from->conf->host);
1835 respondaccounting(rq);
1837 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1840 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1841 username[ATTRVALLEN(attr)] = '\0';
1842 radattr2ascii(userascii, sizeof(userascii), attr);
1844 if (rq->from->conf->rewriteattrregex) {
1845 if (!rewriteusername(rq, username)) {
1846 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1849 len = RADLEN(rq->buf) - 20;
1850 auth = (uint8_t *)(rq->buf + 4);
1851 attrs = rq->buf + 20;
1854 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
1856 to = findserver(&realm, username, code == RAD_Accounting_Request);
1858 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1862 if (realm->message && code == RAD_Access_Request) {
1863 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
1864 respondreject(rq, realm->message);
1865 } else if (realm->accresp && code == RAD_Accounting_Request) {
1866 acclog(attrs, len, rq->from->conf->host);
1867 respondaccounting(rq);
1872 if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
1873 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
1874 rq->from->conf->name, to->conf->name);
1878 if (rqinqueue(to, rq->from, id, code)) {
1879 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
1880 radmsgtype2string(code), rq->from->conf->host, id);
1884 if (code != RAD_Accounting_Request) {
1885 if (!RAND_bytes(newauth, 16)) {
1886 debug(DBG_WARN, "radsrv: failed to generate random auth");
1892 printfchars(NULL, "auth", "%02x ", auth, 16);
1895 attr = attrget(attrs, len, RAD_Attr_User_Password);
1897 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1898 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
1902 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1904 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1905 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
1910 memcpy(rq->origauth, auth, 16);
1911 memcpy(auth, newauth, 16);
1924 int replyh(struct server *server, unsigned char *buf) {
1925 struct client *from;
1928 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
1929 struct sockaddr_storage fromsa;
1930 char tmp[760], stationid[760];
1932 server->connectionok = 1;
1933 server->lostrqs = 0;
1935 i = buf[1]; /* i is the id */
1937 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
1938 && *buf != RAD_Accounting_Response) {
1939 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
1942 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
1944 rq = server->requests + i;
1946 pthread_mutex_lock(&server->newrq_mutex);
1947 if (!rq->buf || !rq->tries) {
1948 pthread_mutex_unlock(&server->newrq_mutex);
1949 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
1954 pthread_mutex_unlock(&server->newrq_mutex);
1955 debug(DBG_INFO, "replyh: already received, ignoring reply");
1959 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
1960 pthread_mutex_unlock(&server->newrq_mutex);
1961 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
1965 len = RADLEN(buf) - 20;
1968 if (!attrvalidate(attrs, len)) {
1969 pthread_mutex_unlock(&server->newrq_mutex);
1970 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
1974 /* Message Authenticator */
1975 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1977 if (ATTRVALLEN(messageauth) != 16) {
1978 pthread_mutex_unlock(&server->newrq_mutex);
1979 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
1982 memcpy(tmp, buf + 4, 16);
1983 memcpy(buf + 4, rq->buf + 4, 16);
1984 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
1985 pthread_mutex_unlock(&server->newrq_mutex);
1986 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
1989 memcpy(buf + 4, tmp, 16);
1990 debug(DBG_DBG, "replyh: message auth ok");
1993 gettimeofday(&server->lastrcv, NULL);
1995 if (*rq->buf == RAD_Status_Server) {
1997 pthread_mutex_unlock(&server->newrq_mutex);
1998 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2002 gettimeofday(&server->lastreply, NULL);
2006 pthread_mutex_unlock(&server->newrq_mutex);
2007 debug(DBG_INFO, "replyh: client gone, ignoring reply");
2011 if (server->conf->rewrite) {
2012 dorewrite(buf, server->conf->rewrite);
2013 len = RADLEN(buf) - 20;
2017 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2018 if (ATTRVALLEN(attr) <= 4)
2021 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
2024 sublen = ATTRVALLEN(attr) - 4;
2025 subattrs = ATTRVAL(attr) + 4;
2026 if (!attrvalidate(subattrs, sublen) ||
2027 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2028 rq, server->conf->secret, from->conf->secret) ||
2029 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2030 rq, server->conf->secret, from->conf->secret))
2034 pthread_mutex_unlock(&server->newrq_mutex);
2035 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2039 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2040 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2042 radattr2ascii(tmp, sizeof(tmp), attr);
2043 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2045 radattr2ascii(stationid, sizeof(stationid), attr);
2046 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2047 radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2049 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2053 buf[1] = (char)rq->origid;
2054 memcpy(buf + 4, rq->origauth, 16);
2056 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2059 if (rq->origusername) {
2060 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2062 pthread_mutex_unlock(&server->newrq_mutex);
2063 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2066 memcpy(username, rq->origusername, strlen(rq->origusername));
2067 len = RADLEN(buf) - 20;
2070 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2074 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2075 pthread_mutex_unlock(&server->newrq_mutex);
2076 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2079 debug(DBG_DBG, "replyh: computed messageauthattr");
2082 fromsa = rq->fromsa; /* only needed for UDP */
2083 /* once we set received = 1, rq may be reused */
2086 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2087 sendreply(from, buf, &fromsa, rq->fromudpsock);
2088 pthread_mutex_unlock(&server->newrq_mutex);
2092 /* code for removing state not finished */
2093 void *clientwr(void *arg) {
2094 struct server *server = (struct server *)arg;
2096 pthread_t clientrdth;
2097 int i, dynconffail = 0;
2100 struct timespec timeout;
2101 struct request statsrvrq;
2102 unsigned char statsrvbuf[38];
2103 struct clsrvconf *conf;
2105 conf = server->conf;
2107 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2112 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2113 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2117 memset(&timeout, 0, sizeof(struct timespec));
2119 if (conf->statusserver) {
2120 memset(&statsrvrq, 0, sizeof(struct request));
2121 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2122 statsrvbuf[0] = RAD_Status_Server;
2124 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2125 statsrvbuf[21] = 18;
2126 gettimeofday(&server->lastrcv, NULL);
2129 if (conf->pdef->connecter) {
2130 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2132 server->connectionok = 1;
2133 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
2134 debug(DBG_ERR, "clientwr: pthread_create failed");
2138 server->connectionok = 1;
2141 pthread_mutex_lock(&server->newrq_mutex);
2142 if (!server->newrq) {
2143 gettimeofday(&now, NULL);
2144 /* random 0-7 seconds */
2145 RAND_bytes(&rnd, 1);
2147 if (conf->statusserver) {
2148 if (!timeout.tv_sec || timeout.tv_sec > server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd)
2149 timeout.tv_sec = server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd;
2151 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2152 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2155 if (timeout.tv_sec > now.tv_sec)
2156 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2158 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2161 if (server->newrq) {
2162 debug(DBG_DBG, "clientwr: got new request");
2167 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2169 pthread_mutex_unlock(&server->newrq_mutex);
2171 for (i = 0; i < MAX_REQUESTS; i++) {
2172 if (server->clientrdgone) {
2173 pthread_join(clientrdth, NULL);
2176 pthread_mutex_lock(&server->newrq_mutex);
2177 while (i < MAX_REQUESTS && !server->requests[i].buf)
2179 if (i == MAX_REQUESTS) {
2180 pthread_mutex_unlock(&server->newrq_mutex);
2183 rq = server->requests + i;
2186 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2188 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2190 /* setting this to NULL means that it can be reused */
2193 pthread_mutex_unlock(&server->newrq_mutex);
2197 gettimeofday(&now, NULL);
2198 if (now.tv_sec < rq->expiry.tv_sec) {
2199 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2200 timeout.tv_sec = rq->expiry.tv_sec;
2201 pthread_mutex_unlock(&server->newrq_mutex);
2205 if (rq->tries == (*rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2206 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2207 if (conf->statusserver) {
2208 if (*rq->buf == RAD_Status_Server) {
2209 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2210 if (server->lostrqs < 255)
2214 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2215 if (server->lostrqs < 255)
2219 /* setting this to NULL means that it can be reused */
2221 pthread_mutex_unlock(&server->newrq_mutex);
2224 pthread_mutex_unlock(&server->newrq_mutex);
2226 rq->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2227 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2228 timeout.tv_sec = rq->expiry.tv_sec;
2230 conf->pdef->clientradput(server, server->requests[i].buf);
2232 if (conf->statusserver) {
2233 gettimeofday(&now, NULL);
2234 if (now.tv_sec - server->lastrcv.tv_sec >= STATUS_SERVER_PERIOD) {
2235 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2236 debug(DBG_WARN, "clientwr: failed to generate random auth");
2239 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2240 if (!statsrvrq.buf) {
2241 debug(DBG_ERR, "clientwr: malloc failed");
2244 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2245 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2246 sendrq(server, &statsrvrq);
2251 conf->servers = NULL;
2252 if (server->dynamiclookuparg) {
2253 removeserversubrealms(realms, conf);
2257 freeclsrvconf(conf);
2259 freeserver(server, 1);
2260 ERR_remove_state(0);
2264 void createlistener(uint8_t type, char *arg) {
2266 struct clsrvconf *listenres;
2267 struct addrinfo *res;
2268 int s = -1, on = 1, *sp = NULL;
2270 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2272 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2274 for (res = listenres->addrinfo; res; res = res->ai_next) {
2275 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2277 debug(DBG_WARN, "createlistener: socket failed");
2280 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2282 if (res->ai_family == AF_INET6)
2283 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2285 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2286 debug(DBG_WARN, "createlistener: bind failed");
2292 sp = malloc(sizeof(int));
2294 debugx(1, DBG_ERR, "malloc failed");
2296 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
2297 debugx(1, DBG_ERR, "pthread_create failed");
2301 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2303 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
2304 listenres->host ? listenres->host : "*", listenres->port);
2305 freeclsrvres(listenres);
2308 void createlisteners(uint8_t type, char **args) {
2312 for (i = 0; args[i]; i++)
2313 createlistener(type, args[i]);
2315 createlistener(type, NULL);
2319 void ssl_info_callback(const SSL *ssl, int where, int ret) {
2323 w = where & ~SSL_ST_MASK;
2325 if (w & SSL_ST_CONNECT)
2327 else if (w & SSL_ST_ACCEPT)
2332 if (where & SSL_CB_LOOP)
2333 debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
2334 else if (where & SSL_CB_ALERT) {
2335 s = (where & SSL_CB_READ) ? "read" : "write";
2336 debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
2338 else if (where & SSL_CB_EXIT) {
2340 debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
2342 debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
2347 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2348 SSL_CTX *ctx = NULL;
2349 STACK_OF(X509_NAME) *calist;
2352 unsigned long error;
2355 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2356 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2357 for (i = 0; i < CRYPTO_num_locks(); i++) {
2358 ssl_lock_count[i] = 0;
2359 pthread_mutex_init(&ssl_locks[i], NULL);
2361 CRYPTO_set_id_callback(ssl_thread_id);
2362 CRYPTO_set_locking_callback(ssl_locking_callback);
2364 SSL_load_error_strings();
2367 while (!RAND_status()) {
2368 time_t t = time(NULL);
2369 pid_t pid = getpid();
2370 RAND_seed((unsigned char *)&t, sizeof(time_t));
2371 RAND_seed((unsigned char *)&pid, sizeof(pid));
2377 ctx = SSL_CTX_new(TLSv1_method());
2379 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2383 ctx = SSL_CTX_new(DTLSv1_method());
2385 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2387 SSL_CTX_set_read_ahead(ctx, 1);
2391 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2395 if (conf->certkeypwd) {
2396 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2397 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2399 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2400 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2401 !SSL_CTX_check_private_key(ctx) ||
2402 !SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2403 while ((error = ERR_get_error()))
2404 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2405 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2410 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2411 if (!conf->cacertfile || calist) {
2412 if (conf->cacertpath) {
2414 calist = sk_X509_NAME_new_null();
2415 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2416 sk_X509_NAME_free(calist);
2422 while ((error = ERR_get_error()))
2423 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2424 debug(DBG_ERR, "tlscreatectx: Error adding CA subjects in TLS context %s", conf->name);
2428 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2429 SSL_CTX_set_client_CA_list(ctx, calist);
2431 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2432 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2434 if (conf->crlcheck) {
2435 x509_s = SSL_CTX_get_cert_store(ctx);
2436 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2439 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
2443 SSL_CTX *tlsgetctx(uint8_t type, char *alt1, char *alt2) {
2446 t = hash_read(tlsconfs, alt1, strlen(alt1));
2448 t = hash_read(tlsconfs, alt2, strlen(alt2));
2456 t->tlsctx = tlscreatectx(RAD_TLS, t);
2460 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2466 struct list *addsrvconfs(char *value, char **names) {
2467 struct list *conflist;
2469 struct list_node *entry;
2470 struct clsrvconf *conf = NULL;
2472 if (!names || !*names)
2475 conflist = list_create();
2477 debug(DBG_ERR, "malloc failed");
2481 for (n = 0; names[n]; n++) {
2482 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2483 conf = (struct clsrvconf *)entry->data;
2484 if (!strcasecmp(names[n], conf->name))
2488 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2489 list_destroy(conflist);
2492 if (!list_push(conflist, conf)) {
2493 debug(DBG_ERR, "malloc failed");
2494 list_destroy(conflist);
2497 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2502 void freerealm(struct realm *realm) {
2506 free(realm->message);
2507 regfree(&realm->regex);
2508 pthread_mutex_destroy(&realm->subrealms_mutex);
2509 if (realm->subrealms)
2510 list_destroy(realm->subrealms);
2511 if (realm->srvconfs) {
2512 /* emptying list without freeing data */
2513 while (list_shift(realm->srvconfs));
2514 list_destroy(realm->srvconfs);
2516 if (realm->accsrvconfs) {
2517 /* emptying list without freeing data */
2518 while (list_shift(realm->accsrvconfs));
2519 list_destroy(realm->accsrvconfs);
2524 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2526 struct realm *realm;
2527 char *s, *regex = NULL;
2529 if (*value == '/') {
2530 /* regexp, remove optional trailing / if present */
2531 if (value[strlen(value) - 1] == '/')
2532 value[strlen(value) - 1] = '\0';
2534 /* not a regexp, let us make it one */
2535 if (*value == '*' && !value[1])
2536 regex = stringcopy(".*", 0);
2538 for (n = 0, s = value; *s;)
2541 regex = malloc(strlen(value) + n + 3);
2544 for (n = 1, s = value; *s; s++) {
2554 debug(DBG_ERR, "malloc failed");
2558 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2561 realm = malloc(sizeof(struct realm));
2563 debug(DBG_ERR, "malloc failed");
2566 memset(realm, 0, sizeof(struct realm));
2568 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
2569 debug(DBG_ERR, "mutex init failed");
2575 realm->name = stringcopy(value, 0);
2577 debug(DBG_ERR, "malloc failed");
2580 if (message && strlen(message) > 253) {
2581 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2584 realm->message = message;
2585 realm->accresp = accresp;
2587 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
2588 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2592 if (servers && *servers) {
2593 realm->srvconfs = addsrvconfs(value, servers);
2594 if (!realm->srvconfs)
2598 if (accservers && *accservers) {
2599 realm->accsrvconfs = addsrvconfs(value, accservers);
2600 if (!realm->accsrvconfs)
2604 if (!list_push(realmlist, realm)) {
2605 debug(DBG_ERR, "malloc failed");
2606 pthread_mutex_destroy(&realm->subrealms_mutex);
2610 debug(DBG_DBG, "addrealm: added realm %s", value);
2620 for (n = 0; servers[n]; n++)
2625 for (n = 0; accservers[n]; n++)
2626 free(accservers[n]);
2632 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2633 struct clsrvconf *srvconf;
2634 struct realm *newrealm = NULL;
2635 char *realmname, *s;
2638 if (!conf->dynamiclookupcommand)
2641 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2642 realmname = strrchr(id, '@');
2648 for (s = realmname; *s; s++)
2649 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2652 pthread_mutex_lock(&realm->subrealms_mutex);
2653 /* exit if we now already got a matching subrealm */
2654 if (id2realm(realm->subrealms, id))
2656 srvconf = malloc(sizeof(struct clsrvconf));
2658 debug(DBG_ERR, "malloc failed");
2662 if (!addserver(srvconf))
2665 if (!realm->subrealms)
2666 realm->subrealms = list_create();
2667 if (!realm->subrealms)
2669 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2673 /* add server and accserver to newrealm */
2674 newrealm->srvconfs = list_create();
2675 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2676 debug(DBG_ERR, "malloc failed");
2679 newrealm->accsrvconfs = list_create();
2680 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2681 debug(DBG_ERR, "malloc failed");
2685 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2687 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2688 debug(DBG_ERR, "pthread_create failed");
2691 pthread_detach(clientth);
2696 list_removedata(realm->subrealms, newrealm);
2697 freerealm(newrealm);
2698 if (!list_first(realm->subrealms)) {
2699 list_destroy(realm->subrealms);
2700 realm->subrealms = NULL;
2703 freeserver(srvconf->servers, 1);
2705 debug(DBG_ERR, "failed to create dynamic server");
2708 pthread_mutex_unlock(&realm->subrealms_mutex);
2711 int dynamicconfig(struct server *server) {
2712 int ok, fd[2], status;
2714 struct clsrvconf *conf = server->conf;
2715 struct gconffile *cf = NULL;
2717 /* for now we only learn hostname/address */
2718 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2721 debug(DBG_ERR, "dynamicconfig: pipe error");
2726 debug(DBG_ERR, "dynamicconfig: fork error");
2730 } else if (pid == 0) {
2733 if (fd[1] != STDOUT_FILENO) {
2734 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2735 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2738 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2739 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2743 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2744 ok = getgenericconfig(&cf, NULL,
2745 "Server", CONF_CBK, confserver_cb, (void *)conf,
2750 if (waitpid(pid, &status, 0) < 0) {
2751 debug(DBG_ERR, "dynamicconfig: wait error");
2756 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2764 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2768 int addmatchcertattr(struct clsrvconf *conf) {
2772 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2773 r = &conf->certcnregex;
2774 v = conf->matchcertattr + 4;
2775 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2776 r = &conf->certuriregex;
2777 v = conf->matchcertattr + 20;
2782 /* regexp, remove optional trailing / if present */
2783 if (v[strlen(v) - 1] == '/')
2784 v[strlen(v) - 1] = '\0';
2788 *r = malloc(sizeof(regex_t));
2790 debug(DBG_ERR, "malloc failed");
2793 if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
2796 debug(DBG_ERR, "failed to compile regular expression %s", v);
2802 int addrewriteattr(struct clsrvconf *conf) {
2805 v = conf->rewriteattr + 11;
2806 if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
2808 /* regexp, remove optional trailing / if present */
2809 if (v[strlen(v) - 1] == '/')
2810 v[strlen(v) - 1] = '\0';
2818 conf->rewriteattrregex = malloc(sizeof(regex_t));
2819 if (!conf->rewriteattrregex) {
2820 debug(DBG_ERR, "malloc failed");
2824 conf->rewriteattrreplacement = stringcopy(w, 0);
2825 if (!conf->rewriteattrreplacement) {
2826 free(conf->rewriteattrregex);
2827 conf->rewriteattrregex = NULL;
2831 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
2832 free(conf->rewriteattrregex);
2833 conf->rewriteattrregex = NULL;
2834 free(conf->rewriteattrreplacement);
2835 conf->rewriteattrreplacement = NULL;
2836 debug(DBG_ERR, "failed to compile regular expression %s", v);
2843 /* should accept both names and numeric values, only numeric right now */
2844 uint8_t attrname2val(char *attrname) {
2847 val = atoi(attrname);
2848 return val > 0 && val < 256 ? val : 0;
2851 /* should accept both names and numeric values, only numeric right now */
2852 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2855 *vendor = atoi(attrname);
2856 s = strchr(attrname, ':');
2861 *type = atoi(s + 1);
2862 return *type >= 0 && *type < 256;
2865 struct rewrite *getrewrite(char *alt1, char *alt2) {
2868 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2870 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2875 void addrewrite(char *value, char **attrs, char **vattrs) {
2876 struct rewrite *rewrite = NULL;
2879 uint32_t *p, *va = NULL;
2883 for (; attrs[n]; n++);
2884 a = malloc((n + 1) * sizeof(uint8_t));
2886 debugx(1, DBG_ERR, "malloc failed");
2888 for (i = 0; i < n; i++) {
2889 if (!(a[i] = attrname2val(attrs[i])))
2890 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
2899 for (; vattrs[n]; n++);
2900 va = malloc((2 * n + 1) * sizeof(uint32_t));
2902 debugx(1, DBG_ERR, "malloc failed");
2904 for (p = va, i = 0; i < n; i++, p += 2) {
2905 if (!vattrname2val(vattrs[i], p, p + 1))
2906 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
2914 rewrite = malloc(sizeof(struct rewrite));
2916 debugx(1, DBG_ERR, "malloc failed");
2917 rewrite->removeattrs = a;
2918 rewrite->removevendorattrs = va;
2921 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2922 debugx(1, DBG_ERR, "malloc failed");
2923 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2926 void freeclsrvconf(struct clsrvconf *conf) {
2932 free(conf->matchcertattr);
2933 if (conf->certcnregex)
2934 regfree(conf->certcnregex);
2935 if (conf->certuriregex)
2936 regfree(conf->certuriregex);
2937 free(conf->confrewrite);
2938 free(conf->rewriteattr);
2939 if (conf->rewriteattrregex)
2940 regfree(conf->rewriteattrregex);
2941 free(conf->rewriteattrreplacement);
2942 free(conf->dynamiclookupcommand);
2943 free(conf->rewrite);
2945 freeaddrinfo(conf->addrinfo);
2946 /* not touching ssl_ctx, clients and servers */
2950 int mergeconfstring(char **dst, char **src) {
2959 t = stringcopy(*dst, 0);
2961 debug(DBG_ERR, "malloc failed");
2969 /* assumes dst is a shallow copy */
2970 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2971 if (!mergeconfstring(&dst->name, &src->name) ||
2972 !mergeconfstring(&dst->host, &src->host) ||
2973 !mergeconfstring(&dst->port, &src->port) ||
2974 !mergeconfstring(&dst->secret, &src->secret) ||
2975 !mergeconfstring(&dst->tls, &src->tls) ||
2976 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2977 !mergeconfstring(&dst->confrewrite, &src->confrewrite) ||
2978 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
2981 dst->pdef = src->pdef;
2982 dst->statusserver = src->statusserver;
2983 dst->certnamecheck = src->certnamecheck;
2984 if (src->retryinterval != 255)
2985 dst->retryinterval = src->retryinterval;
2986 if (src->retrycount != 255)
2987 dst->retrycount = src->retrycount;
2991 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2992 struct clsrvconf *conf;
2993 char *conftype = NULL;
2995 debug(DBG_DBG, "confclient_cb called for %s", block);
2997 conf = malloc(sizeof(struct clsrvconf));
2998 if (!conf || !list_push(clconfs, conf))
2999 debugx(1, DBG_ERR, "malloc failed");
3000 memset(conf, 0, sizeof(struct clsrvconf));
3001 conf->certnamecheck = 1;
3003 if (!getgenericconfig(cf, block,
3004 "type", CONF_STR, &conftype,
3005 "host", CONF_STR, &conf->host,
3006 "secret", CONF_STR, &conf->secret,
3007 "tls", CONF_STR, &conf->tls,
3008 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3009 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3010 "rewrite", CONF_STR, &conf->confrewrite,
3011 "rewriteattribute", CONF_STR, &conf->rewriteattr,
3014 debugx(1, DBG_ERR, "configuration error");
3016 conf->name = stringcopy(val, 0);
3018 conf->host = stringcopy(val, 0);
3019 if (!conf->name || !conf->host)
3020 debugx(1, DBG_ERR, "malloc failed");
3023 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3024 conf->type = protoname2int(conftype);
3025 conf->pdef = &protodefs[conf->type];
3026 if (!conf->pdef->name)
3027 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3030 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3031 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultclient", "default");
3033 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3034 if (conf->matchcertattr && !addmatchcertattr(conf))
3035 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3038 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
3040 if (conf->rewriteattr) {
3041 if (!addrewriteattr(conf))
3042 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3045 if (!resolvepeer(conf, 0))
3046 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3048 if (!conf->secret) {
3049 if (!conf->pdef->secretdefault)
3050 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3051 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3053 debugx(1, DBG_ERR, "malloc failed");
3058 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3059 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3060 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultserver", "default");
3061 if (!conf->ssl_ctx) {
3062 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3065 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3066 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3072 conf->port = stringcopy(conf->pdef->portdefault, 0);
3074 debug(DBG_ERR, "malloc failed");
3079 if (conf->retryinterval == 255)
3080 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3081 if (conf->retrycount == 255)
3082 conf->retrycount = protodefs[conf->type].retrycountdefault;
3084 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
3086 if (!conf->secret) {
3087 if (!conf->pdef->secretdefault) {
3088 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3091 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3092 if (!conf->secret) {
3093 debug(DBG_ERR, "malloc failed");
3098 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3099 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3105 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3106 struct clsrvconf *conf, *resconf;
3107 char *conftype = NULL;
3108 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3110 debug(DBG_DBG, "confserver_cb called for %s", block);
3112 conf = malloc(sizeof(struct clsrvconf));
3114 debug(DBG_ERR, "malloc failed");
3117 memset(conf, 0, sizeof(struct clsrvconf));
3118 resconf = (struct clsrvconf *)arg;
3120 conf->statusserver = resconf->statusserver;
3121 conf->certnamecheck = resconf->certnamecheck;
3123 conf->certnamecheck = 1;
3125 if (!getgenericconfig(cf, block,
3126 "type", CONF_STR, &conftype,
3127 "host", CONF_STR, &conf->host,
3128 "port", CONF_STR, &conf->port,
3129 "secret", CONF_STR, &conf->secret,
3130 "tls", CONF_STR, &conf->tls,
3131 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3132 "rewrite", CONF_STR, &conf->confrewrite,
3133 "StatusServer", CONF_BLN, &conf->statusserver,
3134 "RetryInterval", CONF_LINT, &retryinterval,
3135 "RetryCount", CONF_LINT, &retrycount,
3136 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3137 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3140 debug(DBG_ERR, "configuration error");
3144 conf->name = stringcopy(val, 0);
3146 debug(DBG_ERR, "malloc failed");
3150 conf->host = stringcopy(val, 0);
3152 debug(DBG_ERR, "malloc failed");
3158 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3159 conf->type = protoname2int(conftype);
3160 conf->pdef = &protodefs[conf->type];
3161 if (!conf->pdef->name) {
3162 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3168 if (retryinterval != LONG_MIN) {
3169 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3170 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3173 conf->retryinterval = (uint8_t)retryinterval;
3175 conf->retryinterval = 255;
3177 if (retrycount != LONG_MIN) {
3178 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3179 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3182 conf->retrycount = (uint8_t)retrycount;
3184 conf->retrycount = 255;
3187 if (!mergesrvconf(resconf, conf))
3191 if (conf->dynamiclookupcommand) {
3192 free(conf->dynamiclookupcommand);
3193 conf->dynamiclookupcommand = NULL;
3197 if (resconf || !conf->dynamiclookupcommand) {
3198 if (!compileserverconfig(conf, block))
3205 if (!list_push(srvconfs, conf)) {
3206 debug(DBG_ERR, "malloc failed");
3212 freeclsrvconf(conf);
3216 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3217 char **servers = NULL, **accservers = NULL, *msg = NULL;
3218 uint8_t accresp = 0;
3220 debug(DBG_DBG, "confrealm_cb called for %s", block);
3222 if (!getgenericconfig(cf, block,
3223 "server", CONF_MSTR, &servers,
3224 "accountingServer", CONF_MSTR, &accservers,
3225 "ReplyMessage", CONF_STR, &msg,
3226 "AccountingResponse", CONF_BLN, &accresp,
3229 debugx(1, DBG_ERR, "configuration error");
3231 addrealm(realms, val, servers, accservers, msg, accresp);
3235 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3238 debug(DBG_DBG, "conftls_cb called for %s", block);
3240 conf = malloc(sizeof(struct tls));
3242 debug(DBG_ERR, "conftls_cb: malloc failed");
3245 memset(conf, 0, sizeof(struct tls));
3247 if (!getgenericconfig(cf, block,
3248 "CACertificateFile", CONF_STR, &conf->cacertfile,
3249 "CACertificatePath", CONF_STR, &conf->cacertpath,
3250 "CertificateFile", CONF_STR, &conf->certfile,
3251 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3252 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3253 "CRLCheck", CONF_BLN, &conf->crlcheck,
3256 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3259 if (!conf->certfile || !conf->certkeyfile) {
3260 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3263 if (!conf->cacertfile && !conf->cacertpath) {
3264 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3268 conf->name = stringcopy(val, 0);
3270 debug(DBG_ERR, "conftls_cb: malloc failed");
3274 if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
3275 debug(DBG_ERR, "conftls_cb: malloc failed");
3279 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3283 free(conf->cacertfile);
3284 free(conf->cacertpath);
3285 free(conf->certfile);
3286 free(conf->certkeyfile);
3287 free(conf->certkeypwd);
3292 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3293 char **attrs = NULL, **vattrs = NULL;
3295 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3297 if (!getgenericconfig(cf, block,
3298 "removeAttribute", CONF_MSTR, &attrs,
3299 "removeVendorAttribute", CONF_MSTR, &vattrs,
3302 debugx(1, DBG_ERR, "configuration error");
3303 addrewrite(val, attrs, vattrs);
3307 void getmainconfig(const char *configfile) {
3308 long int loglevel = LONG_MIN;
3309 struct gconffile *cfs;
3311 cfs = openconfigfile(configfile);
3312 memset(&options, 0, sizeof(options));
3314 clconfs = list_create();
3316 debugx(1, DBG_ERR, "malloc failed");
3318 srvconfs = list_create();
3320 debugx(1, DBG_ERR, "malloc failed");
3322 realms = list_create();
3324 debugx(1, DBG_ERR, "malloc failed");
3326 tlsconfs = hash_create();
3328 debugx(1, DBG_ERR, "malloc failed");
3330 rewriteconfs = hash_create();
3332 debugx(1, DBG_ERR, "malloc failed");
3334 if (!getgenericconfig(&cfs, NULL,
3335 "ListenUDP", CONF_MSTR, &options.listenudp,
3336 "ListenTCP", CONF_MSTR, &options.listentcp,
3337 "ListenTLS", CONF_MSTR, &options.listentls,
3338 "ListenDTLS", CONF_MSTR, &options.listendtls,
3339 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
3340 "SourceUDP", CONF_STR, &options.sourceudp,
3341 "SourceTCP", CONF_STR, &options.sourcetcp,
3342 "SourceTLS", CONF_STR, &options.sourcetls,
3343 "SourceDTLS", CONF_STR, &options.sourcedtls,
3344 "LogLevel", CONF_LINT, &loglevel,
3345 "LogDestination", CONF_STR, &options.logdestination,
3346 "LoopPrevention", CONF_BLN, &options.loopprevention,
3347 "Client", CONF_CBK, confclient_cb, NULL,
3348 "Server", CONF_CBK, confserver_cb, NULL,
3349 "Realm", CONF_CBK, confrealm_cb, NULL,
3350 "TLS", CONF_CBK, conftls_cb, NULL,
3351 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3354 debugx(1, DBG_ERR, "configuration error");
3356 if (loglevel != LONG_MIN) {
3357 if (loglevel < 1 || loglevel > 4)
3358 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3359 options.loglevel = (uint8_t)loglevel;
3363 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3366 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3369 *configfile = optarg;
3372 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3373 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3374 *loglevel = *optarg - '0';
3383 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3388 if (!(argc - optind))
3392 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3396 int daemon(int a, int b) {
3404 for (i = 0; i < 3; i++) {
3406 open("/dev/null", O_RDWR);
3412 void *sighandler(void *arg) {
3417 sigemptyset(&sigset);
3418 sigaddset(&sigset, SIGPIPE);
3419 sigwait(&sigset, &sig);
3420 /* only get SIGPIPE right now, so could simplify below code */
3423 /* completely ignoring this */
3426 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3429 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3434 int main(int argc, char **argv) {
3437 struct list_node *entry;
3438 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3439 char *configfile = NULL;
3440 struct clsrvconf *srvconf;
3443 debug_init("radsecproxy");
3444 debug_set_level(DEBUG_LEVEL);
3446 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3448 debug_set_level(loglevel);
3449 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3451 options.loglevel = loglevel;
3452 else if (options.loglevel)
3453 debug_set_level(options.loglevel);
3455 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3456 free(options.logdestination);
3458 if (!list_first(clconfs))
3459 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3460 if (!list_first(realms))
3461 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3464 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3466 if (!foreground && (daemon(0, 0) < 0))
3467 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3469 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3471 sigemptyset(&sigset);
3472 /* exit on all but SIGPIPE, ignore more? */
3473 sigaddset(&sigset, SIGPIPE);
3474 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3475 pthread_create(&sigth, NULL, sighandler, NULL);
3477 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3478 srvconf = (struct clsrvconf *)entry->data;
3479 if (srvconf->dynamiclookupcommand)
3481 if (!addserver(srvconf))
3482 debugx(1, DBG_ERR, "failed to add server");
3483 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3484 (void *)(srvconf->servers)))
3485 debugx(1, DBG_ERR, "pthread_create failed");
3487 /* srcprotores for UDP no longer needed */
3488 if (srcprotores[RAD_UDP]) {
3489 freeaddrinfo(srcprotores[RAD_UDP]);
3490 srcprotores[RAD_UDP] = NULL;
3493 for (i = 0; protodefs[i].name; i++)
3494 if (protodefs[i].initextra)
3495 protodefs[i].initextra();
3497 if (find_clconf_type(RAD_TCP, NULL))
3498 createlisteners(RAD_TCP, options.listentcp);
3500 if (find_clconf_type(RAD_TLS, NULL))
3501 createlisteners(RAD_TLS, options.listentls);
3503 if (find_clconf_type(RAD_DTLS, NULL))
3504 createlisteners(RAD_DTLS, options.listendtls);
3506 if (find_clconf_type(RAD_UDP, NULL)) {
3507 createlisteners(RAD_UDP, options.listenudp);
3508 if (options.listenaccudp)
3509 createlisteners(RAD_UDP, options.listenaccudp);
3512 /* just hang around doing nothing, anything to do here? */