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 connecttcp(struct addrinfo *addrinfo, struct addrinfo *src) {
388 struct addrinfo *res;
391 for (res = addrinfo; res; res = res->ai_next) {
392 s = bindtoaddr(src, res->ai_family, 1, 1);
394 debug(DBG_WARN, "connecttoserver: socket failed");
397 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
399 debug(DBG_WARN, "connecttoserver: connect failed");
406 /* returns 1 if the len first bits are equal, else 0 */
407 int prefixmatch(void *a1, void *a2, uint8_t len) {
408 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
410 if (l && memcmp(a1, a2, l))
415 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
418 /* returns next config with matching address, or NULL */
419 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
420 struct sockaddr_in6 *sa6 = NULL;
421 struct in_addr *a4 = NULL;
422 struct addrinfo *res;
423 struct list_node *entry;
424 struct clsrvconf *conf;
426 if (addr->sa_family == AF_INET6) {
427 sa6 = (struct sockaddr_in6 *)addr;
428 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
429 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
433 a4 = &((struct sockaddr_in *)addr)->sin_addr;
435 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
436 conf = (struct clsrvconf *)entry->data;
437 if (conf->type == type) {
438 if (conf->prefixlen == 255) {
439 for (res = conf->addrinfo; res; res = res->ai_next)
440 if ((a4 && res->ai_family == AF_INET &&
441 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
442 (sa6 && res->ai_family == AF_INET6 &&
443 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
449 res = conf->addrinfo;
451 ((a4 && res->ai_family == AF_INET &&
452 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
453 (sa6 && res->ai_family == AF_INET6 &&
454 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
465 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
466 return find_conf(type, addr, clconfs, cur);
469 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
470 return find_conf(type, addr, srvconfs, cur);
473 /* returns next config of given type, or NULL */
474 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
475 struct list_node *entry;
476 struct clsrvconf *conf;
478 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
479 conf = (struct clsrvconf *)entry->data;
480 if (conf->type == type) {
489 struct queue *newqueue() {
492 q = malloc(sizeof(struct queue));
494 debugx(1, DBG_ERR, "malloc failed");
495 q->entries = list_create();
497 debugx(1, DBG_ERR, "malloc failed");
498 pthread_mutex_init(&q->mutex, NULL);
499 pthread_cond_init(&q->cond, NULL);
503 void removequeue(struct queue *q) {
504 struct list_node *entry;
506 pthread_mutex_lock(&q->mutex);
507 for (entry = list_first(q->entries); entry; entry = list_next(entry))
508 free(((struct reply *)entry)->buf);
509 list_destroy(q->entries);
510 pthread_cond_destroy(&q->cond);
511 pthread_mutex_unlock(&q->mutex);
512 pthread_mutex_destroy(&q->mutex);
515 void freebios(struct queue *q) {
518 pthread_mutex_lock(&q->mutex);
519 while ((bio = (BIO *)list_shift(q->entries)))
521 pthread_mutex_unlock(&q->mutex);
525 struct client *addclient(struct clsrvconf *conf) {
526 struct client *new = malloc(sizeof(struct client));
529 debug(DBG_ERR, "malloc failed");
532 if (!conf->clients) {
533 conf->clients = list_create();
534 if (!conf->clients) {
535 debug(DBG_ERR, "malloc failed");
540 memset(new, 0, sizeof(struct client));
542 if (conf->pdef->addclient)
543 conf->pdef->addclient(new);
545 new->replyq = newqueue();
546 list_push(conf->clients, new);
550 void removeclient(struct client *client) {
551 if (!client || !client->conf->clients)
553 removequeue(client->replyq);
555 freebios(client->rbios);
556 list_removedata(client->conf->clients, client);
560 void removeclientrqs(struct client *client) {
561 struct list_node *entry;
562 struct server *server;
566 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
567 server = ((struct clsrvconf *)entry->data)->servers;
570 pthread_mutex_lock(&server->newrq_mutex);
571 for (i = 0; i < MAX_REQUESTS; i++) {
572 rq = server->requests + i;
573 if (rq->from == client)
576 pthread_mutex_unlock(&server->newrq_mutex);
580 void freeserver(struct server *server, uint8_t destroymutex) {
581 struct request *rq, *end;
586 if (server->requests) {
587 rq = server->requests;
588 for (end = rq + MAX_REQUESTS; rq < end; rq++)
590 free(server->requests);
593 freebios(server->rbios);
594 free(server->dynamiclookuparg);
596 pthread_mutex_destroy(&server->lock);
597 pthread_cond_destroy(&server->newrq_cond);
598 pthread_mutex_destroy(&server->newrq_mutex);
603 int addserver(struct clsrvconf *conf) {
604 struct clsrvconf *res;
608 debug(DBG_ERR, "addserver: currently works with just one server per conf");
611 conf->servers = malloc(sizeof(struct server));
612 if (!conf->servers) {
613 debug(DBG_ERR, "malloc failed");
616 memset(conf->servers, 0, sizeof(struct server));
617 conf->servers->conf = conf;
620 if (type == RAD_DTLS)
621 conf->servers->rbios = newqueue();
623 if (!srcprotores[type]) {
624 res = resolve_hostport(type, *conf->pdef->srcaddrport, NULL);
625 srcprotores[type] = res->addrinfo;
626 res->addrinfo = NULL;
630 conf->servers->sock = -1;
631 if (conf->pdef->addserverextra)
632 conf->pdef->addserverextra(conf);
634 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
635 if (!conf->servers->requests) {
636 debug(DBG_ERR, "malloc failed");
639 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
640 debug(DBG_ERR, "mutex init failed");
643 conf->servers->newrq = 0;
644 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
645 debug(DBG_ERR, "mutex init failed");
646 pthread_mutex_destroy(&conf->servers->lock);
649 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
650 debug(DBG_ERR, "mutex init failed");
651 pthread_mutex_destroy(&conf->servers->newrq_mutex);
652 pthread_mutex_destroy(&conf->servers->lock);
659 freeserver(conf->servers, 0);
660 conf->servers = NULL;
664 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
665 int loc, i, l, n, r = 0;
668 STACK_OF(GENERAL_NAME) *alt;
671 debug(DBG_DBG, "subjectaltnameaddr");
673 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
677 ex = X509_get_ext(cert, loc);
678 alt = X509V3_EXT_d2i(ex);
682 n = sk_GENERAL_NAME_num(alt);
683 for (i = 0; i < n; i++) {
684 gn = sk_GENERAL_NAME_value(alt, i);
685 if (gn->type != GEN_IPADD)
688 v = (char *)ASN1_STRING_data(gn->d.ia5);
689 l = ASN1_STRING_length(gn->d.ia5);
690 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
691 && !memcmp(v, &addr, l)) {
696 GENERAL_NAMES_free(alt);
700 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
707 nm = X509_get_subject_name(cert);
710 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
713 e = X509_NAME_get_entry(nm, loc);
714 t = X509_NAME_ENTRY_get_data(e);
715 v = (char *) ASN1_STRING_data(t);
716 l = ASN1_STRING_length(t);
720 if (l == strlen(exact) && !strncasecmp(exact, v, l))
723 s = stringcopy((char *)v, l);
725 debug(DBG_ERR, "malloc failed");
728 if (regexec(regex, s, 0, NULL, 0)) {
739 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
740 int loc, i, l, n, r = 0;
743 STACK_OF(GENERAL_NAME) *alt;
746 debug(DBG_DBG, "subjectaltnameregexp");
748 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
752 ex = X509_get_ext(cert, loc);
753 alt = X509V3_EXT_d2i(ex);
757 n = sk_GENERAL_NAME_num(alt);
758 for (i = 0; i < n; i++) {
759 gn = sk_GENERAL_NAME_value(alt, i);
760 if (gn->type != type)
763 v = (char *)ASN1_STRING_data(gn->d.ia5);
764 l = ASN1_STRING_length(gn->d.ia5);
768 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
771 if (memcmp(v, exact, l))
774 s = stringcopy((char *)v, l);
776 debug(DBG_ERR, "malloc failed");
779 if (regexec(regex, s, 0, NULL, 0)) {
788 GENERAL_NAMES_free(alt);
792 X509 *verifytlscert(SSL *ssl) {
796 if (SSL_get_verify_result(ssl) != X509_V_OK) {
797 debug(DBG_ERR, "verifytlscert: basic validation failed");
798 while ((error = ERR_get_error()))
799 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
803 cert = SSL_get_peer_certificate(ssl);
805 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
809 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
811 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
812 struct in6_addr addr;
814 if (conf->certnamecheck && conf->prefixlen == 255) {
815 if (inet_pton(AF_INET, conf->host, &addr))
817 else if (inet_pton(AF_INET6, conf->host, &addr))
820 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
823 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
826 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
828 if (!cnregexp(cert, conf->host, NULL)) {
829 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
832 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
835 if (conf->certcnregex) {
836 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
837 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
840 debug(DBG_DBG, "verifyconfcert: CN matching regex");
842 if (conf->certuriregex) {
843 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
844 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
847 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
852 int radsign(unsigned char *rad, unsigned char *sec) {
853 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
854 static unsigned char first = 1;
855 static EVP_MD_CTX mdctx;
859 pthread_mutex_lock(&lock);
861 EVP_MD_CTX_init(&mdctx);
865 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
866 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
867 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
868 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
870 pthread_mutex_unlock(&lock);
874 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
875 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
876 static unsigned char first = 1;
877 static EVP_MD_CTX mdctx;
878 unsigned char hash[EVP_MAX_MD_SIZE];
882 pthread_mutex_lock(&lock);
884 EVP_MD_CTX_init(&mdctx);
890 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
891 EVP_DigestUpdate(&mdctx, rad, 4) &&
892 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
893 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
894 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
895 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
897 !memcmp(hash, rad + 4, 16));
898 pthread_mutex_unlock(&lock);
902 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
903 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
904 static unsigned char first = 1;
905 static HMAC_CTX hmacctx;
907 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
909 pthread_mutex_lock(&lock);
911 HMAC_CTX_init(&hmacctx);
915 memcpy(auth, authattr, 16);
916 memset(authattr, 0, 16);
918 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
919 HMAC_Update(&hmacctx, rad, RADLEN(rad));
920 HMAC_Final(&hmacctx, hash, &md_len);
921 memcpy(authattr, auth, 16);
923 debug(DBG_WARN, "message auth computation failed");
924 pthread_mutex_unlock(&lock);
928 if (memcmp(auth, hash, 16)) {
929 debug(DBG_WARN, "message authenticator, wrong value");
930 pthread_mutex_unlock(&lock);
934 pthread_mutex_unlock(&lock);
938 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
939 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
940 static unsigned char first = 1;
941 static HMAC_CTX hmacctx;
947 pthread_mutex_lock(&lock);
949 HMAC_CTX_init(&hmacctx);
953 memset(authattrval, 0, 16);
955 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
956 HMAC_Update(&hmacctx, rad, RADLEN(rad));
957 HMAC_Final(&hmacctx, authattrval, &md_len);
959 debug(DBG_WARN, "message auth computation failed");
960 pthread_mutex_unlock(&lock);
964 pthread_mutex_unlock(&lock);
968 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
970 if (ATTRTYPE(attrs) == type)
972 length -= ATTRLEN(attrs);
973 attrs += ATTRLEN(attrs);
978 void freerqdata(struct request *rq) {
979 if (rq->origusername)
980 free(rq->origusername);
985 void sendrq(struct server *to, struct request *rq) {
989 pthread_mutex_lock(&to->newrq_mutex);
990 /* might simplify if only try nextid, might be ok */
991 for (i = to->nextid; i < MAX_REQUESTS; i++)
992 if (!to->requests[i].buf)
994 if (i == MAX_REQUESTS) {
995 for (i = 0; i < to->nextid; i++)
996 if (!to->requests[i].buf)
998 if (i == to->nextid) {
999 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
1005 rq->buf[1] = (char)i;
1007 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1008 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1013 if (*rq->buf == RAD_Accounting_Request) {
1014 if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
1015 debug(DBG_WARN, "sendrq: failed to sign Accounting-Request message");
1021 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1022 to->requests[i] = *rq;
1027 debug(DBG_DBG, "sendrq: signalling client writer");
1028 pthread_cond_signal(&to->newrq_cond);
1031 pthread_mutex_unlock(&to->newrq_mutex);
1034 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa, int toudpsock) {
1035 struct reply *reply;
1038 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1040 debug(DBG_WARN, "sendreply: failed to sign message");
1044 reply = malloc(sizeof(struct reply));
1047 debug(DBG_ERR, "sendreply: malloc failed");
1050 memset(reply, 0, sizeof(struct reply));
1053 reply->tosa = *tosa;
1054 reply->toudpsock = toudpsock;
1056 pthread_mutex_lock(&to->replyq->mutex);
1058 first = list_first(to->replyq->entries) == NULL;
1060 if (!list_push(to->replyq->entries, reply)) {
1061 pthread_mutex_unlock(&to->replyq->mutex);
1064 debug(DBG_ERR, "sendreply: malloc failed");
1069 debug(DBG_DBG, "signalling server writer");
1070 pthread_cond_signal(&to->replyq->cond);
1072 pthread_mutex_unlock(&to->replyq->mutex);
1075 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1076 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1077 static unsigned char first = 1;
1078 static EVP_MD_CTX mdctx;
1079 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1080 unsigned int md_len;
1081 uint8_t i, offset = 0, out[128];
1083 pthread_mutex_lock(&lock);
1085 EVP_MD_CTX_init(&mdctx);
1091 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1092 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1093 !EVP_DigestUpdate(&mdctx, input, 16) ||
1094 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1096 pthread_mutex_unlock(&lock);
1099 for (i = 0; i < 16; i++)
1100 out[offset + i] = hash[i] ^ in[offset + i];
1101 input = out + offset - 16;
1106 memcpy(in, out, len);
1107 pthread_mutex_unlock(&lock);
1111 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1112 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1113 static unsigned char first = 1;
1114 static EVP_MD_CTX mdctx;
1115 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1116 unsigned int md_len;
1117 uint8_t i, offset = 0, out[128];
1119 pthread_mutex_lock(&lock);
1121 EVP_MD_CTX_init(&mdctx);
1127 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1128 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1129 !EVP_DigestUpdate(&mdctx, input, 16) ||
1130 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1132 pthread_mutex_unlock(&lock);
1135 for (i = 0; i < 16; i++)
1136 out[offset + i] = hash[i] ^ in[offset + i];
1137 input = in + offset;
1142 memcpy(in, out, len);
1143 pthread_mutex_unlock(&lock);
1147 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1148 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1149 static unsigned char first = 1;
1150 static EVP_MD_CTX mdctx;
1151 unsigned char hash[EVP_MAX_MD_SIZE];
1152 unsigned int md_len;
1155 pthread_mutex_lock(&lock);
1157 EVP_MD_CTX_init(&mdctx);
1162 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1163 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1164 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1167 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1168 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1169 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1170 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1171 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1172 pthread_mutex_unlock(&lock);
1177 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1180 for (i = 0; i < 16; i++)
1183 for (offset = 16; offset < len; offset += 16) {
1185 printf("text + offset - 16 c(%d): ", offset / 16);
1186 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1188 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1189 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1190 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1191 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1193 pthread_mutex_unlock(&lock);
1197 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1200 for (i = 0; i < 16; i++)
1201 text[offset + i] ^= hash[i];
1205 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1208 pthread_mutex_unlock(&lock);
1212 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1213 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1214 static unsigned char first = 1;
1215 static EVP_MD_CTX mdctx;
1216 unsigned char hash[EVP_MAX_MD_SIZE];
1217 unsigned int md_len;
1221 pthread_mutex_lock(&lock);
1223 EVP_MD_CTX_init(&mdctx);
1228 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1229 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1230 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1233 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1234 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1235 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1236 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1237 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1238 pthread_mutex_unlock(&lock);
1243 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1246 for (i = 0; i < 16; i++)
1247 plain[i] = text[i] ^ hash[i];
1249 for (offset = 16; offset < len; offset += 16) {
1251 printf("text + offset - 16 c(%d): ", offset / 16);
1252 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1254 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1255 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1256 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1257 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1259 pthread_mutex_unlock(&lock);
1263 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1266 for (i = 0; i < 16; i++)
1267 plain[offset + i] = text[offset + i] ^ hash[i];
1270 memcpy(text, plain, len);
1272 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1275 pthread_mutex_unlock(&lock);
1279 struct realm *id2realm(struct list *realmlist, char *id) {
1280 struct list_node *entry;
1281 struct realm *realm, *subrealm = NULL;
1283 /* need to do locking for subrealms and check subrealm timers */
1284 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1285 realm = (struct realm *)entry->data;
1286 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1287 pthread_mutex_lock(&realm->subrealms_mutex);
1288 if (realm->subrealms)
1289 subrealm = id2realm(realm->subrealms, id);
1290 pthread_mutex_unlock(&realm->subrealms_mutex);
1291 return subrealm ? subrealm : realm;
1297 /* helper function, only used by removeserversubrealms() */
1298 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1299 struct list_node *entry;
1300 struct realm *realm;
1302 for (entry = list_first(realmlist); entry;) {
1303 realm = (struct realm *)entry->data;
1304 entry = list_next(entry);
1305 if (realm->srvconfs) {
1306 list_removedata(realm->srvconfs, srv);
1307 if (!list_first(realm->srvconfs)) {
1308 list_destroy(realm->srvconfs);
1309 realm->srvconfs = NULL;
1312 if (realm->accsrvconfs) {
1313 list_removedata(realm->accsrvconfs, srv);
1314 if (!list_first(realm->accsrvconfs)) {
1315 list_destroy(realm->accsrvconfs);
1316 realm->accsrvconfs = NULL;
1320 /* remove subrealm if no servers */
1321 if (!realm->srvconfs && !realm->accsrvconfs) {
1322 list_removedata(realmlist, realm);
1328 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1329 struct list_node *entry;
1330 struct realm *realm;
1332 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1333 realm = (struct realm *)entry->data;
1334 pthread_mutex_lock(&realm->subrealms_mutex);
1335 if (realm->subrealms) {
1336 _internal_removeserversubrealms(realm->subrealms, srv);
1337 if (!list_first(realm->subrealms)) {
1338 list_destroy(realm->subrealms);
1339 realm->subrealms = NULL;
1342 pthread_mutex_unlock(&realm->subrealms_mutex);
1346 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1347 struct request *rq = to->requests, *end;
1349 pthread_mutex_lock(&to->newrq_mutex);
1350 for (end = rq + MAX_REQUESTS; rq < end; rq++)
1351 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1353 pthread_mutex_unlock(&to->newrq_mutex);
1358 int attrvalidate(unsigned char *attrs, int length) {
1359 while (length > 1) {
1360 if (ATTRLEN(attrs) < 2) {
1361 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1364 length -= ATTRLEN(attrs);
1366 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1369 attrs += ATTRLEN(attrs);
1372 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1376 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1377 if (len < 16 || len > 128 || len % 16) {
1378 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1382 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1383 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1387 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1389 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1390 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1396 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1399 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1400 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1403 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1404 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1410 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1411 char *oldsecret, char *newsecret) {
1412 unsigned char *attr;
1414 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1415 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1416 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1422 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1426 for (; attrs[0]; attrs += 2)
1427 if (attrs[0] == vendor && attrs[1] == subattr)
1432 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1433 uint8_t alen, sublen, rmlen = 0;
1434 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1437 if (!removevendorattrs)
1440 while (*removevendorattrs && *removevendorattrs != vendor)
1441 removevendorattrs += 2;
1442 if (!*removevendorattrs)
1445 alen = ATTRLEN(attrs);
1447 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1448 /* remove entire vendor attribute */
1449 memmove(attrs, attrs + alen, length - alen);
1454 subattrs = ATTRVAL(attrs) + 4;
1456 if (!attrvalidate(subattrs, sublen)) {
1457 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1462 while (sublen > 1) {
1463 alen = ATTRLEN(subattrs);
1466 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1467 memmove(subattrs, subattrs + alen, length);
1473 ATTRLEN(attrs) -= rmlen;
1477 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1478 uint8_t *attrs, alen;
1479 uint16_t len, rmlen = 0;
1481 if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1484 len = RADLEN(buf) - 20;
1487 alen = ATTRLEN(attrs);
1489 if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1490 memmove(attrs, attrs + alen, len);
1492 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1493 rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1498 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1501 /* returns a pointer to the resized attribute value */
1502 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1503 uint8_t *attrs, *attr, vallen;
1507 len = RADLEN(*buf) - 20;
1510 attr = attrget(attrs, len, type);
1514 vallen = ATTRVALLEN(attr);
1515 if (vallen == newvallen)
1518 len += newvallen - vallen;
1519 if (newvallen > vallen) {
1520 new = realloc(*buf, len + 20);
1522 debug(DBG_ERR, "resizeattr: malloc failed");
1531 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1532 attr[1] = newvallen + 2;
1533 ((uint16_t *)*buf)[1] = htons(len + 20);
1537 int rewriteusername(struct request *rq, char *in) {
1538 size_t nmatch = 10, reslen = 0, start = 0;
1539 regmatch_t pmatch[10], *pfield;
1541 unsigned char *result;
1542 char *out = rq->from->conf->rewriteattrreplacement;
1544 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1545 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1549 rq->origusername = stringcopy(in, 0);
1550 if (!rq->origusername)
1553 for (i = start; out[i]; i++) {
1554 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1555 pfield = &pmatch[out[i + 1] - '0'];
1556 if (pfield->rm_so >= 0) {
1557 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1563 reslen += i - start;
1565 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1571 for (i = start; out[i]; i++) {
1572 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1573 pfield = &pmatch[out[i + 1] - '0'];
1574 if (pfield->rm_so >= 0) {
1575 memcpy(result + reslen, out + start, i - start);
1576 reslen += i - start;
1577 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1578 reslen += pfield->rm_eo - pfield->rm_so;
1585 memcpy(result + reslen, out + start, i - start);
1586 reslen += i - start;
1587 memcpy(in, result, reslen);
1592 const char *radmsgtype2string(uint8_t code) {
1593 static const char *rad_msg_names[] = {
1594 "", "Access-Request", "Access-Accept", "Access-Reject",
1595 "Accounting-Request", "Accounting-Response", "", "",
1596 "", "", "", "Access-Challenge",
1597 "Status-Server", "Status-Client"
1599 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1602 void char2hex(char *h, unsigned char c) {
1603 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1604 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1605 h[0] = hexdigits[c / 16];
1606 h[1] = hexdigits[c % 16];
1610 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
1614 if (!attr || len == 1) {
1619 l = ATTRVALLEN(attr);
1620 s = (char *)ATTRVAL(attr);
1623 for (i = 0; i < l; i++) {
1624 if (s[i] > 31 && s[i] < 127) {
1626 if (d - ascii == len - 1)
1629 if (d - ascii > len - 4)
1634 if (d - ascii == len - 1)
1642 void acclog(unsigned char *attrs, int length, char *host) {
1643 unsigned char *attr;
1646 attr = attrget(attrs, length, RAD_Attr_User_Name);
1648 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1651 radattr2ascii(username, sizeof(username), attr);
1652 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1655 void respondaccounting(struct request *rq) {
1656 unsigned char *resp;
1660 debug(DBG_ERR, "respondaccounting: malloc failed");
1663 memcpy(resp, rq->buf, 20);
1664 resp[0] = RAD_Accounting_Response;
1667 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1668 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1671 void respondstatusserver(struct request *rq) {
1672 unsigned char *resp;
1676 debug(DBG_ERR, "respondstatusserver: malloc failed");
1679 memcpy(resp, rq->buf, 20);
1680 resp[0] = RAD_Access_Accept;
1683 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1684 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1687 void respondreject(struct request *rq, char *message) {
1688 unsigned char *resp;
1691 if (message && *message)
1692 len += 2 + strlen(message);
1696 debug(DBG_ERR, "respondreject: malloc failed");
1699 memcpy(resp, rq->buf, 20);
1700 resp[0] = RAD_Access_Reject;
1701 *(uint16_t *)(resp + 2) = htons(len);
1702 if (message && *message) {
1703 resp[20] = RAD_Attr_Reply_Message;
1704 resp[21] = len - 20;
1705 memcpy(resp + 22, message, len - 22);
1707 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1710 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1711 struct list_node *entry;
1712 struct clsrvconf *server, *best = NULL, *first = NULL;
1714 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1715 server = (struct clsrvconf *)entry->data;
1716 if (!server->servers)
1720 if (!server->servers->connectionok)
1722 if (!server->servers->lostrqs)
1728 if (server->servers->lostrqs < best->servers->lostrqs)
1731 return best ? best : first;
1734 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
1735 struct clsrvconf *srvconf;
1737 *realm = id2realm(realms, id);
1740 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1741 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1744 if (!acc && !srvconf->servers)
1745 adddynamicrealmserver(*realm, srvconf, id);
1746 return srvconf->servers;
1749 /* returns 0 if validation/authentication fails, else 1 */
1750 int radsrv(struct request *rq) {
1751 uint8_t code, id, *auth, *attrs, *attr;
1753 struct server *to = NULL;
1754 char username[254], userascii[760];
1755 unsigned char newauth[16];
1756 struct realm *realm = NULL;
1758 code = *(uint8_t *)rq->buf;
1759 id = *(uint8_t *)(rq->buf + 1);
1760 len = RADLEN(rq->buf);
1761 auth = (uint8_t *)(rq->buf + 4);
1763 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1765 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1766 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1771 attrs = rq->buf + 20;
1773 if (!attrvalidate(attrs, len)) {
1774 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1778 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1779 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
1780 debug(DBG_WARN, "radsrv: message authentication failed");
1784 if (code == RAD_Status_Server) {
1785 respondstatusserver(rq);
1789 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1791 if (code == RAD_Accounting_Request) {
1792 memset(newauth, 0, 16);
1793 if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
1794 debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
1799 if (rq->from->conf->rewrite) {
1800 dorewrite(rq->buf, rq->from->conf->rewrite);
1801 len = RADLEN(rq->buf) - 20;
1804 attr = attrget(attrs, len, RAD_Attr_User_Name);
1806 if (code == RAD_Accounting_Request) {
1807 acclog(attrs, len, rq->from->conf->host);
1808 respondaccounting(rq);
1810 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1813 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1814 username[ATTRVALLEN(attr)] = '\0';
1815 radattr2ascii(userascii, sizeof(userascii), attr);
1817 if (rq->from->conf->rewriteattrregex) {
1818 if (!rewriteusername(rq, username)) {
1819 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1822 len = RADLEN(rq->buf) - 20;
1823 auth = (uint8_t *)(rq->buf + 4);
1824 attrs = rq->buf + 20;
1827 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
1829 to = findserver(&realm, username, code == RAD_Accounting_Request);
1831 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1835 if (realm->message && code == RAD_Access_Request) {
1836 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
1837 respondreject(rq, realm->message);
1838 } else if (realm->accresp && code == RAD_Accounting_Request) {
1839 acclog(attrs, len, rq->from->conf->host);
1840 respondaccounting(rq);
1845 if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
1846 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
1847 rq->from->conf->name, to->conf->name);
1851 if (rqinqueue(to, rq->from, id, code)) {
1852 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
1853 radmsgtype2string(code), rq->from->conf->host, id);
1857 if (code != RAD_Accounting_Request) {
1858 if (!RAND_bytes(newauth, 16)) {
1859 debug(DBG_WARN, "radsrv: failed to generate random auth");
1865 printfchars(NULL, "auth", "%02x ", auth, 16);
1868 attr = attrget(attrs, len, RAD_Attr_User_Password);
1870 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1871 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
1875 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1877 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1878 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
1883 memcpy(rq->origauth, auth, 16);
1884 memcpy(auth, newauth, 16);
1897 int replyh(struct server *server, unsigned char *buf) {
1898 struct client *from;
1901 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
1902 struct sockaddr_storage fromsa;
1903 char tmp[760], stationid[760];
1905 server->connectionok = 1;
1906 server->lostrqs = 0;
1908 i = buf[1]; /* i is the id */
1910 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
1911 && *buf != RAD_Accounting_Response) {
1912 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
1915 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
1917 rq = server->requests + i;
1919 pthread_mutex_lock(&server->newrq_mutex);
1920 if (!rq->buf || !rq->tries) {
1921 pthread_mutex_unlock(&server->newrq_mutex);
1922 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
1927 pthread_mutex_unlock(&server->newrq_mutex);
1928 debug(DBG_INFO, "replyh: already received, ignoring reply");
1932 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
1933 pthread_mutex_unlock(&server->newrq_mutex);
1934 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
1938 len = RADLEN(buf) - 20;
1941 if (!attrvalidate(attrs, len)) {
1942 pthread_mutex_unlock(&server->newrq_mutex);
1943 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
1947 /* Message Authenticator */
1948 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1950 if (ATTRVALLEN(messageauth) != 16) {
1951 pthread_mutex_unlock(&server->newrq_mutex);
1952 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
1955 memcpy(tmp, buf + 4, 16);
1956 memcpy(buf + 4, rq->buf + 4, 16);
1957 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
1958 pthread_mutex_unlock(&server->newrq_mutex);
1959 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
1962 memcpy(buf + 4, tmp, 16);
1963 debug(DBG_DBG, "replyh: message auth ok");
1966 gettimeofday(&server->lastrcv, NULL);
1968 if (*rq->buf == RAD_Status_Server) {
1970 pthread_mutex_unlock(&server->newrq_mutex);
1971 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
1975 gettimeofday(&server->lastreply, NULL);
1979 pthread_mutex_unlock(&server->newrq_mutex);
1980 debug(DBG_INFO, "replyh: client gone, ignoring reply");
1984 if (server->conf->rewrite) {
1985 dorewrite(buf, server->conf->rewrite);
1986 len = RADLEN(buf) - 20;
1990 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1991 if (ATTRVALLEN(attr) <= 4)
1994 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
1997 sublen = ATTRVALLEN(attr) - 4;
1998 subattrs = ATTRVAL(attr) + 4;
1999 if (!attrvalidate(subattrs, sublen) ||
2000 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2001 rq, server->conf->secret, from->conf->secret) ||
2002 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2003 rq, server->conf->secret, from->conf->secret))
2007 pthread_mutex_unlock(&server->newrq_mutex);
2008 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2012 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2013 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2015 radattr2ascii(tmp, sizeof(tmp), attr);
2016 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2018 radattr2ascii(stationid, sizeof(stationid), attr);
2019 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2020 radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2022 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2026 buf[1] = (char)rq->origid;
2027 memcpy(buf + 4, rq->origauth, 16);
2029 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2032 if (rq->origusername) {
2033 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2035 pthread_mutex_unlock(&server->newrq_mutex);
2036 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2039 memcpy(username, rq->origusername, strlen(rq->origusername));
2040 len = RADLEN(buf) - 20;
2043 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2047 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2048 pthread_mutex_unlock(&server->newrq_mutex);
2049 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2052 debug(DBG_DBG, "replyh: computed messageauthattr");
2055 fromsa = rq->fromsa; /* only needed for UDP */
2056 /* once we set received = 1, rq may be reused */
2059 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2060 sendreply(from, buf, &fromsa, rq->fromudpsock);
2061 pthread_mutex_unlock(&server->newrq_mutex);
2065 /* code for removing state not finished */
2066 void *clientwr(void *arg) {
2067 struct server *server = (struct server *)arg;
2069 pthread_t clientrdth;
2070 int i, dynconffail = 0;
2073 struct timespec timeout;
2074 struct request statsrvrq;
2075 unsigned char statsrvbuf[38];
2076 struct clsrvconf *conf;
2078 conf = server->conf;
2080 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2085 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2086 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2090 memset(&timeout, 0, sizeof(struct timespec));
2092 if (conf->statusserver) {
2093 memset(&statsrvrq, 0, sizeof(struct request));
2094 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2095 statsrvbuf[0] = RAD_Status_Server;
2097 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2098 statsrvbuf[21] = 18;
2099 gettimeofday(&server->lastrcv, NULL);
2102 if (conf->pdef->connecter) {
2103 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2105 server->connectionok = 1;
2106 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
2107 debug(DBG_ERR, "clientwr: pthread_create failed");
2111 server->connectionok = 1;
2114 pthread_mutex_lock(&server->newrq_mutex);
2115 if (!server->newrq) {
2116 gettimeofday(&now, NULL);
2117 /* random 0-7 seconds */
2118 RAND_bytes(&rnd, 1);
2120 if (conf->statusserver) {
2121 if (!timeout.tv_sec || timeout.tv_sec > server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd)
2122 timeout.tv_sec = server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd;
2124 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2125 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2128 if (timeout.tv_sec > now.tv_sec)
2129 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2131 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2134 if (server->newrq) {
2135 debug(DBG_DBG, "clientwr: got new request");
2140 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2142 pthread_mutex_unlock(&server->newrq_mutex);
2144 for (i = 0; i < MAX_REQUESTS; i++) {
2145 if (server->clientrdgone) {
2146 pthread_join(clientrdth, NULL);
2149 pthread_mutex_lock(&server->newrq_mutex);
2150 while (i < MAX_REQUESTS && !server->requests[i].buf)
2152 if (i == MAX_REQUESTS) {
2153 pthread_mutex_unlock(&server->newrq_mutex);
2156 rq = server->requests + i;
2159 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2161 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2163 /* setting this to NULL means that it can be reused */
2166 pthread_mutex_unlock(&server->newrq_mutex);
2170 gettimeofday(&now, NULL);
2171 if (now.tv_sec < rq->expiry.tv_sec) {
2172 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2173 timeout.tv_sec = rq->expiry.tv_sec;
2174 pthread_mutex_unlock(&server->newrq_mutex);
2178 if (rq->tries == (*rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2179 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2180 if (conf->statusserver) {
2181 if (*rq->buf == RAD_Status_Server) {
2182 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2183 if (server->lostrqs < 255)
2187 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2188 if (server->lostrqs < 255)
2192 /* setting this to NULL means that it can be reused */
2194 pthread_mutex_unlock(&server->newrq_mutex);
2197 pthread_mutex_unlock(&server->newrq_mutex);
2199 rq->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2200 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2201 timeout.tv_sec = rq->expiry.tv_sec;
2203 conf->pdef->clientradput(server, server->requests[i].buf);
2205 if (conf->statusserver) {
2206 gettimeofday(&now, NULL);
2207 if (now.tv_sec - server->lastrcv.tv_sec >= STATUS_SERVER_PERIOD) {
2208 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2209 debug(DBG_WARN, "clientwr: failed to generate random auth");
2212 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2213 if (!statsrvrq.buf) {
2214 debug(DBG_ERR, "clientwr: malloc failed");
2217 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2218 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2219 sendrq(server, &statsrvrq);
2224 conf->servers = NULL;
2225 if (server->dynamiclookuparg) {
2226 removeserversubrealms(realms, conf);
2230 freeclsrvconf(conf);
2232 freeserver(server, 1);
2233 ERR_remove_state(0);
2237 void createlistener(uint8_t type, char *arg) {
2239 struct clsrvconf *listenres;
2240 struct addrinfo *res;
2241 int s = -1, on = 1, *sp = NULL;
2243 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2245 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2247 for (res = listenres->addrinfo; res; res = res->ai_next) {
2248 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2250 debug(DBG_WARN, "createlistener: socket failed");
2253 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2255 if (res->ai_family == AF_INET6)
2256 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2258 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2259 debug(DBG_WARN, "createlistener: bind failed");
2265 sp = malloc(sizeof(int));
2267 debugx(1, DBG_ERR, "malloc failed");
2269 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
2270 debugx(1, DBG_ERR, "pthread_create failed");
2274 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2276 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
2277 listenres->host ? listenres->host : "*", listenres->port);
2278 freeclsrvres(listenres);
2281 void createlisteners(uint8_t type, char **args) {
2285 for (i = 0; args[i]; i++)
2286 createlistener(type, args[i]);
2288 createlistener(type, NULL);
2292 void ssl_info_callback(const SSL *ssl, int where, int ret) {
2296 w = where & ~SSL_ST_MASK;
2298 if (w & SSL_ST_CONNECT)
2300 else if (w & SSL_ST_ACCEPT)
2305 if (where & SSL_CB_LOOP)
2306 debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
2307 else if (where & SSL_CB_ALERT) {
2308 s = (where & SSL_CB_READ) ? "read" : "write";
2309 debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
2311 else if (where & SSL_CB_EXIT) {
2313 debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
2315 debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
2320 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2321 SSL_CTX *ctx = NULL;
2322 STACK_OF(X509_NAME) *calist;
2325 unsigned long error;
2328 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2329 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2330 for (i = 0; i < CRYPTO_num_locks(); i++) {
2331 ssl_lock_count[i] = 0;
2332 pthread_mutex_init(&ssl_locks[i], NULL);
2334 CRYPTO_set_id_callback(ssl_thread_id);
2335 CRYPTO_set_locking_callback(ssl_locking_callback);
2337 SSL_load_error_strings();
2340 while (!RAND_status()) {
2341 time_t t = time(NULL);
2342 pid_t pid = getpid();
2343 RAND_seed((unsigned char *)&t, sizeof(time_t));
2344 RAND_seed((unsigned char *)&pid, sizeof(pid));
2350 ctx = SSL_CTX_new(TLSv1_method());
2352 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2356 ctx = SSL_CTX_new(DTLSv1_method());
2358 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2360 SSL_CTX_set_read_ahead(ctx, 1);
2364 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2368 if (conf->certkeypwd) {
2369 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2370 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2372 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2373 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2374 !SSL_CTX_check_private_key(ctx) ||
2375 !SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2376 while ((error = ERR_get_error()))
2377 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2378 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2383 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2384 if (!conf->cacertfile || calist) {
2385 if (conf->cacertpath) {
2387 calist = sk_X509_NAME_new_null();
2388 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2389 sk_X509_NAME_free(calist);
2395 while ((error = ERR_get_error()))
2396 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2397 debug(DBG_ERR, "tlscreatectx: Error adding CA subjects in TLS context %s", conf->name);
2401 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2402 SSL_CTX_set_client_CA_list(ctx, calist);
2404 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2405 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2407 if (conf->crlcheck) {
2408 x509_s = SSL_CTX_get_cert_store(ctx);
2409 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2412 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
2416 SSL_CTX *tlsgetctx(uint8_t type, char *alt1, char *alt2) {
2419 t = hash_read(tlsconfs, alt1, strlen(alt1));
2421 t = hash_read(tlsconfs, alt2, strlen(alt2));
2429 t->tlsctx = tlscreatectx(RAD_TLS, t);
2433 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2439 struct list *addsrvconfs(char *value, char **names) {
2440 struct list *conflist;
2442 struct list_node *entry;
2443 struct clsrvconf *conf = NULL;
2445 if (!names || !*names)
2448 conflist = list_create();
2450 debug(DBG_ERR, "malloc failed");
2454 for (n = 0; names[n]; n++) {
2455 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2456 conf = (struct clsrvconf *)entry->data;
2457 if (!strcasecmp(names[n], conf->name))
2461 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2462 list_destroy(conflist);
2465 if (!list_push(conflist, conf)) {
2466 debug(DBG_ERR, "malloc failed");
2467 list_destroy(conflist);
2470 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2475 void freerealm(struct realm *realm) {
2479 free(realm->message);
2480 regfree(&realm->regex);
2481 pthread_mutex_destroy(&realm->subrealms_mutex);
2482 if (realm->subrealms)
2483 list_destroy(realm->subrealms);
2484 if (realm->srvconfs) {
2485 /* emptying list without freeing data */
2486 while (list_shift(realm->srvconfs));
2487 list_destroy(realm->srvconfs);
2489 if (realm->accsrvconfs) {
2490 /* emptying list without freeing data */
2491 while (list_shift(realm->accsrvconfs));
2492 list_destroy(realm->accsrvconfs);
2497 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2499 struct realm *realm;
2500 char *s, *regex = NULL;
2502 if (*value == '/') {
2503 /* regexp, remove optional trailing / if present */
2504 if (value[strlen(value) - 1] == '/')
2505 value[strlen(value) - 1] = '\0';
2507 /* not a regexp, let us make it one */
2508 if (*value == '*' && !value[1])
2509 regex = stringcopy(".*", 0);
2511 for (n = 0, s = value; *s;)
2514 regex = malloc(strlen(value) + n + 3);
2517 for (n = 1, s = value; *s; s++) {
2527 debug(DBG_ERR, "malloc failed");
2531 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2534 realm = malloc(sizeof(struct realm));
2536 debug(DBG_ERR, "malloc failed");
2539 memset(realm, 0, sizeof(struct realm));
2541 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
2542 debug(DBG_ERR, "mutex init failed");
2548 realm->name = stringcopy(value, 0);
2550 debug(DBG_ERR, "malloc failed");
2553 if (message && strlen(message) > 253) {
2554 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2557 realm->message = message;
2558 realm->accresp = accresp;
2560 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
2561 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2565 if (servers && *servers) {
2566 realm->srvconfs = addsrvconfs(value, servers);
2567 if (!realm->srvconfs)
2571 if (accservers && *accservers) {
2572 realm->accsrvconfs = addsrvconfs(value, accservers);
2573 if (!realm->accsrvconfs)
2577 if (!list_push(realmlist, realm)) {
2578 debug(DBG_ERR, "malloc failed");
2579 pthread_mutex_destroy(&realm->subrealms_mutex);
2583 debug(DBG_DBG, "addrealm: added realm %s", value);
2593 for (n = 0; servers[n]; n++)
2598 for (n = 0; accservers[n]; n++)
2599 free(accservers[n]);
2605 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2606 struct clsrvconf *srvconf;
2607 struct realm *newrealm = NULL;
2608 char *realmname, *s;
2611 if (!conf->dynamiclookupcommand)
2614 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2615 realmname = strrchr(id, '@');
2621 for (s = realmname; *s; s++)
2622 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2625 pthread_mutex_lock(&realm->subrealms_mutex);
2626 /* exit if we now already got a matching subrealm */
2627 if (id2realm(realm->subrealms, id))
2629 srvconf = malloc(sizeof(struct clsrvconf));
2631 debug(DBG_ERR, "malloc failed");
2635 if (!addserver(srvconf))
2638 if (!realm->subrealms)
2639 realm->subrealms = list_create();
2640 if (!realm->subrealms)
2642 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2646 /* add server and accserver to newrealm */
2647 newrealm->srvconfs = list_create();
2648 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2649 debug(DBG_ERR, "malloc failed");
2652 newrealm->accsrvconfs = list_create();
2653 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2654 debug(DBG_ERR, "malloc failed");
2658 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2660 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2661 debug(DBG_ERR, "pthread_create failed");
2664 pthread_detach(clientth);
2669 list_removedata(realm->subrealms, newrealm);
2670 freerealm(newrealm);
2671 if (!list_first(realm->subrealms)) {
2672 list_destroy(realm->subrealms);
2673 realm->subrealms = NULL;
2676 freeserver(srvconf->servers, 1);
2678 debug(DBG_ERR, "failed to create dynamic server");
2681 pthread_mutex_unlock(&realm->subrealms_mutex);
2684 int dynamicconfig(struct server *server) {
2685 int ok, fd[2], status;
2687 struct clsrvconf *conf = server->conf;
2688 struct gconffile *cf = NULL;
2690 /* for now we only learn hostname/address */
2691 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2694 debug(DBG_ERR, "dynamicconfig: pipe error");
2699 debug(DBG_ERR, "dynamicconfig: fork error");
2703 } else if (pid == 0) {
2706 if (fd[1] != STDOUT_FILENO) {
2707 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2708 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2711 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2712 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2716 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2717 ok = getgenericconfig(&cf, NULL,
2718 "Server", CONF_CBK, confserver_cb, (void *)conf,
2723 if (waitpid(pid, &status, 0) < 0) {
2724 debug(DBG_ERR, "dynamicconfig: wait error");
2729 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2737 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2741 int addmatchcertattr(struct clsrvconf *conf) {
2745 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2746 r = &conf->certcnregex;
2747 v = conf->matchcertattr + 4;
2748 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2749 r = &conf->certuriregex;
2750 v = conf->matchcertattr + 20;
2755 /* regexp, remove optional trailing / if present */
2756 if (v[strlen(v) - 1] == '/')
2757 v[strlen(v) - 1] = '\0';
2761 *r = malloc(sizeof(regex_t));
2763 debug(DBG_ERR, "malloc failed");
2766 if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
2769 debug(DBG_ERR, "failed to compile regular expression %s", v);
2775 int addrewriteattr(struct clsrvconf *conf) {
2778 v = conf->rewriteattr + 11;
2779 if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
2781 /* regexp, remove optional trailing / if present */
2782 if (v[strlen(v) - 1] == '/')
2783 v[strlen(v) - 1] = '\0';
2791 conf->rewriteattrregex = malloc(sizeof(regex_t));
2792 if (!conf->rewriteattrregex) {
2793 debug(DBG_ERR, "malloc failed");
2797 conf->rewriteattrreplacement = stringcopy(w, 0);
2798 if (!conf->rewriteattrreplacement) {
2799 free(conf->rewriteattrregex);
2800 conf->rewriteattrregex = NULL;
2804 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
2805 free(conf->rewriteattrregex);
2806 conf->rewriteattrregex = NULL;
2807 free(conf->rewriteattrreplacement);
2808 conf->rewriteattrreplacement = NULL;
2809 debug(DBG_ERR, "failed to compile regular expression %s", v);
2816 /* should accept both names and numeric values, only numeric right now */
2817 uint8_t attrname2val(char *attrname) {
2820 val = atoi(attrname);
2821 return val > 0 && val < 256 ? val : 0;
2824 /* should accept both names and numeric values, only numeric right now */
2825 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2828 *vendor = atoi(attrname);
2829 s = strchr(attrname, ':');
2834 *type = atoi(s + 1);
2835 return *type >= 0 && *type < 256;
2838 struct rewrite *getrewrite(char *alt1, char *alt2) {
2841 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2843 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2848 void addrewrite(char *value, char **attrs, char **vattrs) {
2849 struct rewrite *rewrite = NULL;
2852 uint32_t *p, *va = NULL;
2856 for (; attrs[n]; n++);
2857 a = malloc((n + 1) * sizeof(uint8_t));
2859 debugx(1, DBG_ERR, "malloc failed");
2861 for (i = 0; i < n; i++) {
2862 if (!(a[i] = attrname2val(attrs[i])))
2863 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
2872 for (; vattrs[n]; n++);
2873 va = malloc((2 * n + 1) * sizeof(uint32_t));
2875 debugx(1, DBG_ERR, "malloc failed");
2877 for (p = va, i = 0; i < n; i++, p += 2) {
2878 if (!vattrname2val(vattrs[i], p, p + 1))
2879 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
2887 rewrite = malloc(sizeof(struct rewrite));
2889 debugx(1, DBG_ERR, "malloc failed");
2890 rewrite->removeattrs = a;
2891 rewrite->removevendorattrs = va;
2894 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2895 debugx(1, DBG_ERR, "malloc failed");
2896 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2899 void freeclsrvconf(struct clsrvconf *conf) {
2905 free(conf->matchcertattr);
2906 if (conf->certcnregex)
2907 regfree(conf->certcnregex);
2908 if (conf->certuriregex)
2909 regfree(conf->certuriregex);
2910 free(conf->confrewrite);
2911 free(conf->rewriteattr);
2912 if (conf->rewriteattrregex)
2913 regfree(conf->rewriteattrregex);
2914 free(conf->rewriteattrreplacement);
2915 free(conf->dynamiclookupcommand);
2916 free(conf->rewrite);
2918 freeaddrinfo(conf->addrinfo);
2919 /* not touching ssl_ctx, clients and servers */
2923 int mergeconfstring(char **dst, char **src) {
2932 t = stringcopy(*dst, 0);
2934 debug(DBG_ERR, "malloc failed");
2942 /* assumes dst is a shallow copy */
2943 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2944 if (!mergeconfstring(&dst->name, &src->name) ||
2945 !mergeconfstring(&dst->host, &src->host) ||
2946 !mergeconfstring(&dst->port, &src->port) ||
2947 !mergeconfstring(&dst->secret, &src->secret) ||
2948 !mergeconfstring(&dst->tls, &src->tls) ||
2949 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2950 !mergeconfstring(&dst->confrewrite, &src->confrewrite) ||
2951 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
2954 dst->pdef = src->pdef;
2955 dst->statusserver = src->statusserver;
2956 dst->certnamecheck = src->certnamecheck;
2957 if (src->retryinterval != 255)
2958 dst->retryinterval = src->retryinterval;
2959 if (src->retrycount != 255)
2960 dst->retrycount = src->retrycount;
2964 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2965 struct clsrvconf *conf;
2966 char *conftype = NULL;
2968 debug(DBG_DBG, "confclient_cb called for %s", block);
2970 conf = malloc(sizeof(struct clsrvconf));
2971 if (!conf || !list_push(clconfs, conf))
2972 debugx(1, DBG_ERR, "malloc failed");
2973 memset(conf, 0, sizeof(struct clsrvconf));
2974 conf->certnamecheck = 1;
2976 if (!getgenericconfig(cf, block,
2977 "type", CONF_STR, &conftype,
2978 "host", CONF_STR, &conf->host,
2979 "secret", CONF_STR, &conf->secret,
2980 "tls", CONF_STR, &conf->tls,
2981 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
2982 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2983 "rewrite", CONF_STR, &conf->confrewrite,
2984 "rewriteattribute", CONF_STR, &conf->rewriteattr,
2987 debugx(1, DBG_ERR, "configuration error");
2989 conf->name = stringcopy(val, 0);
2991 conf->host = stringcopy(val, 0);
2992 if (!conf->name || !conf->host)
2993 debugx(1, DBG_ERR, "malloc failed");
2996 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2997 conf->type = protoname2int(conftype);
2998 conf->pdef = &protodefs[conf->type];
2999 if (!conf->pdef->name)
3000 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3003 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3004 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultclient", "default");
3006 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3007 if (conf->matchcertattr && !addmatchcertattr(conf))
3008 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3011 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
3013 if (conf->rewriteattr) {
3014 if (!addrewriteattr(conf))
3015 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3018 if (!resolvepeer(conf, 0))
3019 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3021 if (!conf->secret) {
3022 if (!conf->pdef->secretdefault)
3023 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3024 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3026 debugx(1, DBG_ERR, "malloc failed");
3031 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3032 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3033 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultserver", "default");
3034 if (!conf->ssl_ctx) {
3035 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3038 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3039 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3045 conf->port = stringcopy(conf->pdef->portdefault, 0);
3047 debug(DBG_ERR, "malloc failed");
3052 if (conf->retryinterval == 255)
3053 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3054 if (conf->retrycount == 255)
3055 conf->retrycount = protodefs[conf->type].retrycountdefault;
3057 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
3059 if (!conf->secret) {
3060 if (!conf->pdef->secretdefault) {
3061 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3064 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3065 if (!conf->secret) {
3066 debug(DBG_ERR, "malloc failed");
3071 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3072 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3078 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3079 struct clsrvconf *conf, *resconf;
3080 char *conftype = NULL;
3081 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3083 debug(DBG_DBG, "confserver_cb called for %s", block);
3085 conf = malloc(sizeof(struct clsrvconf));
3087 debug(DBG_ERR, "malloc failed");
3090 memset(conf, 0, sizeof(struct clsrvconf));
3091 resconf = (struct clsrvconf *)arg;
3093 conf->statusserver = resconf->statusserver;
3094 conf->certnamecheck = resconf->certnamecheck;
3096 conf->certnamecheck = 1;
3098 if (!getgenericconfig(cf, block,
3099 "type", CONF_STR, &conftype,
3100 "host", CONF_STR, &conf->host,
3101 "port", CONF_STR, &conf->port,
3102 "secret", CONF_STR, &conf->secret,
3103 "tls", CONF_STR, &conf->tls,
3104 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3105 "rewrite", CONF_STR, &conf->confrewrite,
3106 "StatusServer", CONF_BLN, &conf->statusserver,
3107 "RetryInterval", CONF_LINT, &retryinterval,
3108 "RetryCount", CONF_LINT, &retrycount,
3109 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3110 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3113 debug(DBG_ERR, "configuration error");
3117 conf->name = stringcopy(val, 0);
3119 debug(DBG_ERR, "malloc failed");
3123 conf->host = stringcopy(val, 0);
3125 debug(DBG_ERR, "malloc failed");
3131 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3132 conf->type = protoname2int(conftype);
3133 conf->pdef = &protodefs[conf->type];
3134 if (!conf->pdef->name) {
3135 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3141 if (retryinterval != LONG_MIN) {
3142 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3143 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3146 conf->retryinterval = (uint8_t)retryinterval;
3148 conf->retryinterval = 255;
3150 if (retrycount != LONG_MIN) {
3151 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3152 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3155 conf->retrycount = (uint8_t)retrycount;
3157 conf->retrycount = 255;
3160 if (!mergesrvconf(resconf, conf))
3164 if (conf->dynamiclookupcommand) {
3165 free(conf->dynamiclookupcommand);
3166 conf->dynamiclookupcommand = NULL;
3170 if (resconf || !conf->dynamiclookupcommand) {
3171 if (!compileserverconfig(conf, block))
3178 if (!list_push(srvconfs, conf)) {
3179 debug(DBG_ERR, "malloc failed");
3185 freeclsrvconf(conf);
3189 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3190 char **servers = NULL, **accservers = NULL, *msg = NULL;
3191 uint8_t accresp = 0;
3193 debug(DBG_DBG, "confrealm_cb called for %s", block);
3195 if (!getgenericconfig(cf, block,
3196 "server", CONF_MSTR, &servers,
3197 "accountingServer", CONF_MSTR, &accservers,
3198 "ReplyMessage", CONF_STR, &msg,
3199 "AccountingResponse", CONF_BLN, &accresp,
3202 debugx(1, DBG_ERR, "configuration error");
3204 addrealm(realms, val, servers, accservers, msg, accresp);
3208 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3211 debug(DBG_DBG, "conftls_cb called for %s", block);
3213 conf = malloc(sizeof(struct tls));
3215 debug(DBG_ERR, "conftls_cb: malloc failed");
3218 memset(conf, 0, sizeof(struct tls));
3220 if (!getgenericconfig(cf, block,
3221 "CACertificateFile", CONF_STR, &conf->cacertfile,
3222 "CACertificatePath", CONF_STR, &conf->cacertpath,
3223 "CertificateFile", CONF_STR, &conf->certfile,
3224 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3225 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3226 "CRLCheck", CONF_BLN, &conf->crlcheck,
3229 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3232 if (!conf->certfile || !conf->certkeyfile) {
3233 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3236 if (!conf->cacertfile && !conf->cacertpath) {
3237 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3241 conf->name = stringcopy(val, 0);
3243 debug(DBG_ERR, "conftls_cb: malloc failed");
3247 if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
3248 debug(DBG_ERR, "conftls_cb: malloc failed");
3252 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3256 free(conf->cacertfile);
3257 free(conf->cacertpath);
3258 free(conf->certfile);
3259 free(conf->certkeyfile);
3260 free(conf->certkeypwd);
3265 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3266 char **attrs = NULL, **vattrs = NULL;
3268 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3270 if (!getgenericconfig(cf, block,
3271 "removeAttribute", CONF_MSTR, &attrs,
3272 "removeVendorAttribute", CONF_MSTR, &vattrs,
3275 debugx(1, DBG_ERR, "configuration error");
3276 addrewrite(val, attrs, vattrs);
3280 void getmainconfig(const char *configfile) {
3281 long int loglevel = LONG_MIN;
3282 struct gconffile *cfs;
3284 cfs = openconfigfile(configfile);
3285 memset(&options, 0, sizeof(options));
3287 clconfs = list_create();
3289 debugx(1, DBG_ERR, "malloc failed");
3291 srvconfs = list_create();
3293 debugx(1, DBG_ERR, "malloc failed");
3295 realms = list_create();
3297 debugx(1, DBG_ERR, "malloc failed");
3299 tlsconfs = hash_create();
3301 debugx(1, DBG_ERR, "malloc failed");
3303 rewriteconfs = hash_create();
3305 debugx(1, DBG_ERR, "malloc failed");
3307 if (!getgenericconfig(&cfs, NULL,
3308 "ListenUDP", CONF_MSTR, &options.listenudp,
3309 "ListenTCP", CONF_MSTR, &options.listentcp,
3310 "ListenTLS", CONF_MSTR, &options.listentls,
3311 "ListenDTLS", CONF_MSTR, &options.listendtls,
3312 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
3313 "SourceUDP", CONF_STR, &options.sourceudp,
3314 "SourceTCP", CONF_STR, &options.sourcetcp,
3315 "SourceTLS", CONF_STR, &options.sourcetls,
3316 "SourceDTLS", CONF_STR, &options.sourcedtls,
3317 "LogLevel", CONF_LINT, &loglevel,
3318 "LogDestination", CONF_STR, &options.logdestination,
3319 "LoopPrevention", CONF_BLN, &options.loopprevention,
3320 "Client", CONF_CBK, confclient_cb, NULL,
3321 "Server", CONF_CBK, confserver_cb, NULL,
3322 "Realm", CONF_CBK, confrealm_cb, NULL,
3323 "TLS", CONF_CBK, conftls_cb, NULL,
3324 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3327 debugx(1, DBG_ERR, "configuration error");
3329 if (loglevel != LONG_MIN) {
3330 if (loglevel < 1 || loglevel > 4)
3331 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3332 options.loglevel = (uint8_t)loglevel;
3336 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3339 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3342 *configfile = optarg;
3345 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3346 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3347 *loglevel = *optarg - '0';
3356 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3361 if (!(argc - optind))
3365 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3369 int daemon(int a, int b) {
3377 for (i = 0; i < 3; i++) {
3379 open("/dev/null", O_RDWR);
3385 void *sighandler(void *arg) {
3390 sigemptyset(&sigset);
3391 sigaddset(&sigset, SIGPIPE);
3392 sigwait(&sigset, &sig);
3393 /* only get SIGPIPE right now, so could simplify below code */
3396 /* completely ignoring this */
3399 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3402 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3407 int main(int argc, char **argv) {
3410 struct list_node *entry;
3411 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3412 char *configfile = NULL;
3413 struct clsrvconf *srvconf;
3416 debug_init("radsecproxy");
3417 debug_set_level(DEBUG_LEVEL);
3419 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3421 debug_set_level(loglevel);
3422 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3424 options.loglevel = loglevel;
3425 else if (options.loglevel)
3426 debug_set_level(options.loglevel);
3428 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3429 free(options.logdestination);
3431 if (!list_first(clconfs))
3432 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3433 if (!list_first(realms))
3434 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3437 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3439 if (!foreground && (daemon(0, 0) < 0))
3440 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3442 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3444 sigemptyset(&sigset);
3445 /* exit on all but SIGPIPE, ignore more? */
3446 sigaddset(&sigset, SIGPIPE);
3447 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3448 pthread_create(&sigth, NULL, sighandler, NULL);
3450 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3451 srvconf = (struct clsrvconf *)entry->data;
3452 if (srvconf->dynamiclookupcommand)
3454 if (!addserver(srvconf))
3455 debugx(1, DBG_ERR, "failed to add server");
3456 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3457 (void *)(srvconf->servers)))
3458 debugx(1, DBG_ERR, "pthread_create failed");
3460 /* srcprotores for UDP no longer needed */
3461 if (srcprotores[RAD_UDP]) {
3462 freeaddrinfo(srcprotores[RAD_UDP]);
3463 srcprotores[RAD_UDP] = NULL;
3466 for (i = 0; protodefs[i].name; i++)
3467 if (protodefs[i].initextra)
3468 protodefs[i].initextra();
3470 if (find_clconf_type(RAD_TCP, NULL))
3471 createlisteners(RAD_TCP, options.listentcp);
3473 if (find_clconf_type(RAD_TLS, NULL))
3474 createlisteners(RAD_TLS, options.listentls);
3476 if (find_clconf_type(RAD_DTLS, NULL))
3477 createlisteners(RAD_DTLS, options.listendtls);
3479 if (find_clconf_type(RAD_UDP, NULL)) {
3480 createlisteners(RAD_UDP, options.listenudp);
3481 if (options.listenaccudp)
3482 createlisteners(RAD_UDP, options.listenaccudp);
3485 /* just hang around doing nothing, anything to do here? */