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>
66 #include "radsecproxy.h"
72 static struct options options;
73 static struct list *clconfs, *srvconfs;
74 struct list *realms, *tlsconfs, *rewriteconfs;
76 static struct addrinfo *srcprotores[4] = { NULL, NULL, NULL, NULL };
78 static pthread_mutex_t tlsconfs_lock;
79 static pthread_mutex_t *ssl_locks = NULL;
80 static long *ssl_lock_count;
84 /* minimum required declarations to avoid reordering code */
85 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
86 int dynamicconfig(struct server *server);
87 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
88 void freerealm(struct realm *realm);
89 void freeclsrvconf(struct clsrvconf *conf);
90 void freerqdata(struct request *rq);
92 static const struct protodefs protodefs[] = {
93 { "udp", /* UDP, assuming RAD_UDP defined as 0 */
94 NULL, /* secretdefault */
95 SOCK_DGRAM, /* socktype */
96 "1812", /* portdefault */
97 REQUEST_RETRY_COUNT, /* retrycountdefault */
98 10, /* retrycountmax */
99 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
100 60, /* retryintervalmax */
101 udpserverrd, /* listener */
102 &options.sourceudp, /* srcaddrport */
103 NULL, /* connecter */
104 NULL, /* clientconnreader */
105 clientradputudp, /* clientradput */
106 addclientudp, /* addclient */
107 addserverextraudp, /* addserverextra */
108 initextraudp /* initextra */
110 { "tls", /* TLS, assuming RAD_TLS defined as 1 */
111 "mysecret", /* secretdefault */
112 SOCK_STREAM, /* socktype */
113 "2083", /* portdefault */
114 0, /* retrycountdefault */
115 0, /* retrycountmax */
116 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
117 60, /* retryintervalmax */
118 tlslistener, /* listener */
119 &options.sourcetls, /* srcaddrport */
120 tlsconnect, /* connecter */
121 tlsclientrd, /* clientconnreader */
122 clientradputtls, /* clientradput */
123 NULL, /* addclient */
124 NULL, /* addserverextra */
127 { "tcp", /* TCP, assuming RAD_TCP defined as 2 */
128 NULL, /* secretdefault */
129 SOCK_STREAM, /* socktype */
130 "1812", /* portdefault */
131 0, /* retrycountdefault */
132 0, /* retrycountmax */
133 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
134 60, /* retryintervalmax */
135 tcplistener, /* listener */
136 &options.sourcetcp, /* srcaddrport */
137 tcpconnect, /* connecter */
138 tcpclientrd, /* clientconnreader */
139 clientradputtcp, /* clientradput */
140 NULL, /* addclient */
141 NULL, /* addserverextra */
144 { "dtls", /* DTLS, assuming RAD_DTLS defined as 3 */
145 "mysecret", /* secretdefault */
146 SOCK_DGRAM, /* socktype */
147 "2083", /* portdefault */
148 REQUEST_RETRY_COUNT, /* retrycountdefault */
149 10, /* retrycountmax */
150 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
151 60, /* retryintervalmax */
152 udpdtlsserverrd, /* listener */
153 &options.sourcedtls, /* srcaddrport */
154 dtlsconnect, /* connecter */
155 dtlsclientrd, /* clientconnreader */
156 clientradputdtls, /* clientradput */
157 addclientdtls, /* addclient */
158 addserverextradtls, /* addserverextra */
159 initextradtls /* initextra */
165 uint8_t protoname2int(const char *name) {
168 for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
172 /* callbacks for making OpenSSL thread safe */
173 unsigned long ssl_thread_id() {
174 return (unsigned long)pthread_self();
177 void ssl_locking_callback(int mode, int type, const char *file, int line) {
178 if (mode & CRYPTO_LOCK) {
179 pthread_mutex_lock(&ssl_locks[type]);
180 ssl_lock_count[type]++;
182 pthread_mutex_unlock(&ssl_locks[type]);
185 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
186 int pwdlen = strlen(userdata);
187 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
189 memcpy(buf, userdata, pwdlen);
193 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
198 err_cert = X509_STORE_CTX_get_current_cert(ctx);
199 err = X509_STORE_CTX_get_error(ctx);
200 depth = X509_STORE_CTX_get_error_depth(ctx);
202 if (depth > MAX_CERT_DEPTH) {
204 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
205 X509_STORE_CTX_set_error(ctx, err);
209 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
210 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
213 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
214 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
215 debug(DBG_WARN, "\tIssuer=%s", buf);
217 case X509_V_ERR_CERT_NOT_YET_VALID:
218 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
219 debug(DBG_WARN, "\tCertificate not yet valid");
221 case X509_V_ERR_CERT_HAS_EXPIRED:
222 debug(DBG_WARN, "Certificate has expired");
224 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
225 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
230 printf("certificate verify returns %d\n", ok);
235 struct addrinfo *getsrcprotores(uint8_t type) {
236 return srcprotores[type];
239 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
240 struct addrinfo hints, *addrinfo, *res;
244 slash = conf->host ? strchr(conf->host, '/') : NULL;
248 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
252 if (*s < '0' || *s > '9') {
253 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
256 plen = atoi(slash + 1);
257 if (plen < 0 || plen > 128) {
258 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
263 memset(&hints, 0, sizeof(hints));
264 hints.ai_socktype = conf->pdef->socktype;
265 hints.ai_family = AF_UNSPEC;
266 hints.ai_flags = ai_flags;
267 if (!conf->host && !conf->port) {
268 /* getaddrinfo() doesn't like host and port to be NULL */
269 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
270 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
273 for (res = addrinfo; res; res = res->ai_next) {
274 switch (res->ai_family) {
276 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
279 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
285 hints.ai_flags |= AI_NUMERICHOST;
286 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
287 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
292 switch (addrinfo->ai_family) {
295 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
296 freeaddrinfo(addrinfo);
303 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
304 freeaddrinfo(addrinfo);
307 conf->prefixlen = plen;
309 conf->prefixlen = 255;
312 freeaddrinfo(conf->addrinfo);
313 conf->addrinfo = addrinfo;
317 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
322 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
326 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
328 debugx(1, DBG_ERR, "no ] matching initial [");
332 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
335 debugx(1, DBG_ERR, "missing host/address");
337 conf->host = stringcopy(field, p - field);
340 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
341 debugx(1, DBG_ERR, "unexpected character after ]");
344 /* port number or service name is specified */;
346 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
348 debugx(1, DBG_ERR, "syntax error, : but no following port");
349 conf->port = stringcopy(field, p - field);
351 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
355 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
356 struct clsrvconf *conf;
358 conf = malloc(sizeof(struct clsrvconf));
360 debugx(1, DBG_ERR, "malloc failed");
361 memset(conf, 0, sizeof(struct clsrvconf));
363 conf->pdef = &protodefs[conf->type];
365 parsehostport(lconf, conf, default_port);
366 if (!strcmp(conf->host, "*")) {
371 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
372 if (!resolvepeer(conf, AI_PASSIVE))
373 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
377 void freeclsrvres(struct clsrvconf *res) {
381 freeaddrinfo(res->addrinfo);
385 int connecttcp(struct addrinfo *addrinfo, struct addrinfo *src) {
387 struct addrinfo *res;
390 for (res = addrinfo; res; res = res->ai_next) {
391 s = bindtoaddr(src, res->ai_family, 1, 1);
393 debug(DBG_WARN, "connecttoserver: socket failed");
396 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
398 debug(DBG_WARN, "connecttoserver: connect failed");
405 /* returns 1 if the len first bits are equal, else 0 */
406 int prefixmatch(void *a1, void *a2, uint8_t len) {
407 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
409 if (l && memcmp(a1, a2, l))
414 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
417 /* returns next config with matching address, or NULL */
418 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
419 struct sockaddr_in6 *sa6 = NULL;
420 struct in_addr *a4 = NULL;
421 struct addrinfo *res;
422 struct list_node *entry;
423 struct clsrvconf *conf;
425 if (addr->sa_family == AF_INET6) {
426 sa6 = (struct sockaddr_in6 *)addr;
427 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
428 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
432 a4 = &((struct sockaddr_in *)addr)->sin_addr;
434 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
435 conf = (struct clsrvconf *)entry->data;
436 if (conf->type == type) {
437 if (conf->prefixlen == 255) {
438 for (res = conf->addrinfo; res; res = res->ai_next)
439 if ((a4 && res->ai_family == AF_INET &&
440 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
441 (sa6 && res->ai_family == AF_INET6 &&
442 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
448 res = conf->addrinfo;
450 ((a4 && res->ai_family == AF_INET &&
451 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
452 (sa6 && res->ai_family == AF_INET6 &&
453 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
464 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
465 return find_conf(type, addr, clconfs, cur);
468 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
469 return find_conf(type, addr, srvconfs, cur);
472 /* returns next config of given type, or NULL */
473 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
474 struct list_node *entry;
475 struct clsrvconf *conf;
477 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
478 conf = (struct clsrvconf *)entry->data;
479 if (conf->type == type) {
488 struct queue *newqueue() {
491 q = malloc(sizeof(struct queue));
493 debugx(1, DBG_ERR, "malloc failed");
494 q->entries = list_create();
496 debugx(1, DBG_ERR, "malloc failed");
497 pthread_mutex_init(&q->mutex, NULL);
498 pthread_cond_init(&q->cond, NULL);
502 void removequeue(struct queue *q) {
503 struct list_node *entry;
505 pthread_mutex_lock(&q->mutex);
506 for (entry = list_first(q->entries); entry; entry = list_next(entry))
507 free(((struct reply *)entry)->buf);
508 list_destroy(q->entries);
509 pthread_cond_destroy(&q->cond);
510 pthread_mutex_unlock(&q->mutex);
511 pthread_mutex_destroy(&q->mutex);
514 void freebios(struct queue *q) {
517 pthread_mutex_lock(&q->mutex);
518 while ((bio = (BIO *)list_shift(q->entries)))
520 pthread_mutex_unlock(&q->mutex);
524 struct client *addclient(struct clsrvconf *conf) {
525 struct client *new = malloc(sizeof(struct client));
528 debug(DBG_ERR, "malloc failed");
531 if (!conf->clients) {
532 conf->clients = list_create();
533 if (!conf->clients) {
534 debug(DBG_ERR, "malloc failed");
539 memset(new, 0, sizeof(struct client));
541 if (conf->pdef->addclient)
542 conf->pdef->addclient(new);
544 new->replyq = newqueue();
545 list_push(conf->clients, new);
549 void removeclient(struct client *client) {
550 if (!client || !client->conf->clients)
552 removequeue(client->replyq);
554 freebios(client->rbios);
555 list_removedata(client->conf->clients, client);
559 void removeclientrqs(struct client *client) {
560 struct list_node *entry;
561 struct server *server;
565 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
566 server = ((struct clsrvconf *)entry->data)->servers;
569 pthread_mutex_lock(&server->newrq_mutex);
570 for (i = 0; i < MAX_REQUESTS; i++) {
571 rq = server->requests + i;
572 if (rq->from == client)
575 pthread_mutex_unlock(&server->newrq_mutex);
579 void freeserver(struct server *server, uint8_t destroymutex) {
580 struct request *rq, *end;
585 if (server->requests) {
586 rq = server->requests;
587 for (end = rq + MAX_REQUESTS; rq < end; rq++)
589 free(server->requests);
592 freebios(server->rbios);
593 free(server->dynamiclookuparg);
595 pthread_mutex_destroy(&server->lock);
596 pthread_cond_destroy(&server->newrq_cond);
597 pthread_mutex_destroy(&server->newrq_mutex);
602 int addserver(struct clsrvconf *conf) {
603 struct clsrvconf *res;
607 debug(DBG_ERR, "addserver: currently works with just one server per conf");
610 conf->servers = malloc(sizeof(struct server));
611 if (!conf->servers) {
612 debug(DBG_ERR, "malloc failed");
615 memset(conf->servers, 0, sizeof(struct server));
616 conf->servers->conf = conf;
619 if (type == RAD_DTLS)
620 conf->servers->rbios = newqueue();
622 if (!srcprotores[type]) {
623 res = resolve_hostport(type, *conf->pdef->srcaddrport, NULL);
624 srcprotores[type] = res->addrinfo;
625 res->addrinfo = NULL;
629 conf->servers->sock = -1;
630 if (conf->pdef->addserverextra)
631 conf->pdef->addserverextra(conf);
633 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
634 if (!conf->servers->requests) {
635 debug(DBG_ERR, "malloc failed");
638 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
639 debug(DBG_ERR, "mutex init failed");
642 conf->servers->newrq = 0;
643 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
644 debug(DBG_ERR, "mutex init failed");
645 pthread_mutex_destroy(&conf->servers->lock);
648 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
649 debug(DBG_ERR, "mutex init failed");
650 pthread_mutex_destroy(&conf->servers->newrq_mutex);
651 pthread_mutex_destroy(&conf->servers->lock);
658 freeserver(conf->servers, 0);
659 conf->servers = NULL;
663 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
664 int loc, i, l, n, r = 0;
667 STACK_OF(GENERAL_NAME) *alt;
670 debug(DBG_DBG, "subjectaltnameaddr");
672 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
676 ex = X509_get_ext(cert, loc);
677 alt = X509V3_EXT_d2i(ex);
681 n = sk_GENERAL_NAME_num(alt);
682 for (i = 0; i < n; i++) {
683 gn = sk_GENERAL_NAME_value(alt, i);
684 if (gn->type != GEN_IPADD)
687 v = (char *)ASN1_STRING_data(gn->d.ia5);
688 l = ASN1_STRING_length(gn->d.ia5);
689 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
690 && !memcmp(v, &addr, l)) {
695 GENERAL_NAMES_free(alt);
699 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
706 nm = X509_get_subject_name(cert);
709 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
712 e = X509_NAME_get_entry(nm, loc);
713 t = X509_NAME_ENTRY_get_data(e);
714 v = (char *) ASN1_STRING_data(t);
715 l = ASN1_STRING_length(t);
719 if (l == strlen(exact) && !strncasecmp(exact, v, l))
722 s = stringcopy((char *)v, l);
724 debug(DBG_ERR, "malloc failed");
727 if (regexec(regex, s, 0, NULL, 0)) {
738 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
739 int loc, i, l, n, r = 0;
742 STACK_OF(GENERAL_NAME) *alt;
745 debug(DBG_DBG, "subjectaltnameregexp");
747 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
751 ex = X509_get_ext(cert, loc);
752 alt = X509V3_EXT_d2i(ex);
756 n = sk_GENERAL_NAME_num(alt);
757 for (i = 0; i < n; i++) {
758 gn = sk_GENERAL_NAME_value(alt, i);
759 if (gn->type != type)
762 v = (char *)ASN1_STRING_data(gn->d.ia5);
763 l = ASN1_STRING_length(gn->d.ia5);
767 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
770 if (memcmp(v, exact, l))
773 s = stringcopy((char *)v, l);
775 debug(DBG_ERR, "malloc failed");
778 if (regexec(regex, s, 0, NULL, 0)) {
787 GENERAL_NAMES_free(alt);
791 X509 *verifytlscert(SSL *ssl) {
795 if (SSL_get_verify_result(ssl) != X509_V_OK) {
796 debug(DBG_ERR, "verifytlscert: basic validation failed");
797 while ((error = ERR_get_error()))
798 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
802 cert = SSL_get_peer_certificate(ssl);
804 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
808 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
810 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
811 struct in6_addr addr;
813 if (conf->certnamecheck && conf->prefixlen == 255) {
814 if (inet_pton(AF_INET, conf->host, &addr))
816 else if (inet_pton(AF_INET6, conf->host, &addr))
819 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
822 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
825 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
827 if (!cnregexp(cert, conf->host, NULL)) {
828 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
831 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
834 if (conf->certcnregex) {
835 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
836 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
839 debug(DBG_DBG, "verifyconfcert: CN matching regex");
841 if (conf->certuriregex) {
842 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
843 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
846 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
851 int radsign(unsigned char *rad, unsigned char *sec) {
852 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
853 static unsigned char first = 1;
854 static EVP_MD_CTX mdctx;
858 pthread_mutex_lock(&lock);
860 EVP_MD_CTX_init(&mdctx);
864 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
865 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
866 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
867 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
869 pthread_mutex_unlock(&lock);
873 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
874 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
875 static unsigned char first = 1;
876 static EVP_MD_CTX mdctx;
877 unsigned char hash[EVP_MAX_MD_SIZE];
881 pthread_mutex_lock(&lock);
883 EVP_MD_CTX_init(&mdctx);
889 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
890 EVP_DigestUpdate(&mdctx, rad, 4) &&
891 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
892 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
893 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
894 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
896 !memcmp(hash, rad + 4, 16));
897 pthread_mutex_unlock(&lock);
901 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
902 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
903 static unsigned char first = 1;
904 static HMAC_CTX hmacctx;
906 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
908 pthread_mutex_lock(&lock);
910 HMAC_CTX_init(&hmacctx);
914 memcpy(auth, authattr, 16);
915 memset(authattr, 0, 16);
917 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
918 HMAC_Update(&hmacctx, rad, RADLEN(rad));
919 HMAC_Final(&hmacctx, hash, &md_len);
920 memcpy(authattr, auth, 16);
922 debug(DBG_WARN, "message auth computation failed");
923 pthread_mutex_unlock(&lock);
927 if (memcmp(auth, hash, 16)) {
928 debug(DBG_WARN, "message authenticator, wrong value");
929 pthread_mutex_unlock(&lock);
933 pthread_mutex_unlock(&lock);
937 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
938 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
939 static unsigned char first = 1;
940 static HMAC_CTX hmacctx;
946 pthread_mutex_lock(&lock);
948 HMAC_CTX_init(&hmacctx);
952 memset(authattrval, 0, 16);
954 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
955 HMAC_Update(&hmacctx, rad, RADLEN(rad));
956 HMAC_Final(&hmacctx, authattrval, &md_len);
958 debug(DBG_WARN, "message auth computation failed");
959 pthread_mutex_unlock(&lock);
963 pthread_mutex_unlock(&lock);
967 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
969 if (ATTRTYPE(attrs) == type)
971 length -= ATTRLEN(attrs);
972 attrs += ATTRLEN(attrs);
977 void freerqdata(struct request *rq) {
978 if (rq->origusername)
979 free(rq->origusername);
984 void sendrq(struct server *to, struct request *rq) {
988 pthread_mutex_lock(&to->newrq_mutex);
989 /* might simplify if only try nextid, might be ok */
990 for (i = to->nextid; i < MAX_REQUESTS; i++)
991 if (!to->requests[i].buf)
993 if (i == MAX_REQUESTS) {
994 for (i = 0; i < to->nextid; i++)
995 if (!to->requests[i].buf)
997 if (i == to->nextid) {
998 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
1004 rq->buf[1] = (char)i;
1006 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1007 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1012 if (*rq->buf == RAD_Accounting_Request) {
1013 if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
1014 debug(DBG_WARN, "sendrq: failed to sign Accounting-Request message");
1020 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1021 to->requests[i] = *rq;
1026 debug(DBG_DBG, "sendrq: signalling client writer");
1027 pthread_cond_signal(&to->newrq_cond);
1030 pthread_mutex_unlock(&to->newrq_mutex);
1033 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa, int toudpsock) {
1034 struct reply *reply;
1037 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1039 debug(DBG_WARN, "sendreply: failed to sign message");
1043 reply = malloc(sizeof(struct reply));
1046 debug(DBG_ERR, "sendreply: malloc failed");
1049 memset(reply, 0, sizeof(struct reply));
1052 reply->tosa = *tosa;
1053 reply->toudpsock = toudpsock;
1055 pthread_mutex_lock(&to->replyq->mutex);
1057 first = list_first(to->replyq->entries) == NULL;
1059 if (!list_push(to->replyq->entries, reply)) {
1060 pthread_mutex_unlock(&to->replyq->mutex);
1063 debug(DBG_ERR, "sendreply: malloc failed");
1068 debug(DBG_DBG, "signalling server writer");
1069 pthread_cond_signal(&to->replyq->cond);
1071 pthread_mutex_unlock(&to->replyq->mutex);
1074 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1075 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1076 static unsigned char first = 1;
1077 static EVP_MD_CTX mdctx;
1078 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1079 unsigned int md_len;
1080 uint8_t i, offset = 0, out[128];
1082 pthread_mutex_lock(&lock);
1084 EVP_MD_CTX_init(&mdctx);
1090 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1091 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1092 !EVP_DigestUpdate(&mdctx, input, 16) ||
1093 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1095 pthread_mutex_unlock(&lock);
1098 for (i = 0; i < 16; i++)
1099 out[offset + i] = hash[i] ^ in[offset + i];
1100 input = out + offset - 16;
1105 memcpy(in, out, len);
1106 pthread_mutex_unlock(&lock);
1110 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1111 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1112 static unsigned char first = 1;
1113 static EVP_MD_CTX mdctx;
1114 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1115 unsigned int md_len;
1116 uint8_t i, offset = 0, out[128];
1118 pthread_mutex_lock(&lock);
1120 EVP_MD_CTX_init(&mdctx);
1126 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1127 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1128 !EVP_DigestUpdate(&mdctx, input, 16) ||
1129 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1131 pthread_mutex_unlock(&lock);
1134 for (i = 0; i < 16; i++)
1135 out[offset + i] = hash[i] ^ in[offset + i];
1136 input = in + offset;
1141 memcpy(in, out, len);
1142 pthread_mutex_unlock(&lock);
1146 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1147 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1148 static unsigned char first = 1;
1149 static EVP_MD_CTX mdctx;
1150 unsigned char hash[EVP_MAX_MD_SIZE];
1151 unsigned int md_len;
1154 pthread_mutex_lock(&lock);
1156 EVP_MD_CTX_init(&mdctx);
1161 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1162 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1163 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1166 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1167 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1168 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1169 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1170 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1171 pthread_mutex_unlock(&lock);
1176 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1179 for (i = 0; i < 16; i++)
1182 for (offset = 16; offset < len; offset += 16) {
1184 printf("text + offset - 16 c(%d): ", offset / 16);
1185 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1187 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1188 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1189 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1190 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1192 pthread_mutex_unlock(&lock);
1196 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1199 for (i = 0; i < 16; i++)
1200 text[offset + i] ^= hash[i];
1204 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1207 pthread_mutex_unlock(&lock);
1211 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1212 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1213 static unsigned char first = 1;
1214 static EVP_MD_CTX mdctx;
1215 unsigned char hash[EVP_MAX_MD_SIZE];
1216 unsigned int md_len;
1220 pthread_mutex_lock(&lock);
1222 EVP_MD_CTX_init(&mdctx);
1227 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1228 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1229 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1232 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1233 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1234 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1235 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1236 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1237 pthread_mutex_unlock(&lock);
1242 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1245 for (i = 0; i < 16; i++)
1246 plain[i] = text[i] ^ hash[i];
1248 for (offset = 16; offset < len; offset += 16) {
1250 printf("text + offset - 16 c(%d): ", offset / 16);
1251 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1253 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1254 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1255 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1256 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1258 pthread_mutex_unlock(&lock);
1262 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1265 for (i = 0; i < 16; i++)
1266 plain[offset + i] = text[offset + i] ^ hash[i];
1269 memcpy(text, plain, len);
1271 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1274 pthread_mutex_unlock(&lock);
1278 struct realm *id2realm(struct list *realmlist, char *id) {
1279 struct list_node *entry;
1280 struct realm *realm, *subrealm = NULL;
1282 /* need to do locking for subrealms and check subrealm timers */
1283 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1284 realm = (struct realm *)entry->data;
1285 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1286 pthread_mutex_lock(&realm->subrealms_mutex);
1287 if (realm->subrealms)
1288 subrealm = id2realm(realm->subrealms, id);
1289 pthread_mutex_unlock(&realm->subrealms_mutex);
1290 return subrealm ? subrealm : realm;
1296 /* helper function, only used by removeserversubrealms() */
1297 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1298 struct list_node *entry;
1299 struct realm *realm;
1301 for (entry = list_first(realmlist); entry;) {
1302 realm = (struct realm *)entry->data;
1303 entry = list_next(entry);
1304 if (realm->srvconfs) {
1305 list_removedata(realm->srvconfs, srv);
1306 if (!list_first(realm->srvconfs)) {
1307 list_destroy(realm->srvconfs);
1308 realm->srvconfs = NULL;
1311 if (realm->accsrvconfs) {
1312 list_removedata(realm->accsrvconfs, srv);
1313 if (!list_first(realm->accsrvconfs)) {
1314 list_destroy(realm->accsrvconfs);
1315 realm->accsrvconfs = NULL;
1319 /* remove subrealm if no servers */
1320 if (!realm->srvconfs && !realm->accsrvconfs) {
1321 list_removedata(realmlist, realm);
1327 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1328 struct list_node *entry;
1329 struct realm *realm;
1331 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1332 realm = (struct realm *)entry->data;
1333 pthread_mutex_lock(&realm->subrealms_mutex);
1334 if (realm->subrealms) {
1335 _internal_removeserversubrealms(realm->subrealms, srv);
1336 if (!list_first(realm->subrealms)) {
1337 list_destroy(realm->subrealms);
1338 realm->subrealms = NULL;
1341 pthread_mutex_unlock(&realm->subrealms_mutex);
1345 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1346 struct request *rq = to->requests, *end;
1348 pthread_mutex_lock(&to->newrq_mutex);
1349 for (end = rq + MAX_REQUESTS; rq < end; rq++)
1350 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1352 pthread_mutex_unlock(&to->newrq_mutex);
1357 int attrvalidate(unsigned char *attrs, int length) {
1358 while (length > 1) {
1359 if (ATTRLEN(attrs) < 2) {
1360 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1363 length -= ATTRLEN(attrs);
1365 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1368 attrs += ATTRLEN(attrs);
1371 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1375 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1376 if (len < 16 || len > 128 || len % 16) {
1377 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1381 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1382 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1386 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1388 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1389 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1395 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1398 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1399 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1402 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1403 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1409 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1410 char *oldsecret, char *newsecret) {
1411 unsigned char *attr;
1413 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1414 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1415 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1421 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1425 for (; attrs[0]; attrs += 2)
1426 if (attrs[0] == vendor && attrs[1] == subattr)
1431 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1432 uint8_t alen, sublen, rmlen = 0;
1433 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1436 if (!removevendorattrs)
1439 while (*removevendorattrs && *removevendorattrs != vendor)
1440 removevendorattrs += 2;
1441 if (!*removevendorattrs)
1444 alen = ATTRLEN(attrs);
1446 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1447 /* remove entire vendor attribute */
1448 memmove(attrs, attrs + alen, length - alen);
1453 subattrs = ATTRVAL(attrs) + 4;
1455 if (!attrvalidate(subattrs, sublen)) {
1456 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1461 while (sublen > 1) {
1462 alen = ATTRLEN(subattrs);
1465 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1466 memmove(subattrs, subattrs + alen, length);
1472 ATTRLEN(attrs) -= rmlen;
1476 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1477 uint8_t *attrs, alen;
1478 uint16_t len, rmlen = 0;
1480 if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1483 len = RADLEN(buf) - 20;
1486 alen = ATTRLEN(attrs);
1488 if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1489 memmove(attrs, attrs + alen, len);
1491 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1492 rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1497 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1500 /* returns a pointer to the resized attribute value */
1501 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1502 uint8_t *attrs, *attr, vallen;
1506 len = RADLEN(*buf) - 20;
1509 attr = attrget(attrs, len, type);
1513 vallen = ATTRVALLEN(attr);
1514 if (vallen == newvallen)
1517 len += newvallen - vallen;
1518 if (newvallen > vallen) {
1519 new = realloc(*buf, len + 20);
1521 debug(DBG_ERR, "resizeattr: malloc failed");
1530 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1531 attr[1] = newvallen + 2;
1532 ((uint16_t *)*buf)[1] = htons(len + 20);
1536 int rewriteusername(struct request *rq, char *in) {
1537 size_t nmatch = 10, reslen = 0, start = 0;
1538 regmatch_t pmatch[10], *pfield;
1540 unsigned char *result;
1541 char *out = rq->from->conf->rewriteattrreplacement;
1543 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1544 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1548 rq->origusername = stringcopy(in, 0);
1549 if (!rq->origusername)
1552 for (i = start; out[i]; i++) {
1553 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1554 pfield = &pmatch[out[i + 1] - '0'];
1555 if (pfield->rm_so >= 0) {
1556 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1562 reslen += i - start;
1564 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1570 for (i = start; out[i]; i++) {
1571 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1572 pfield = &pmatch[out[i + 1] - '0'];
1573 if (pfield->rm_so >= 0) {
1574 memcpy(result + reslen, out + start, i - start);
1575 reslen += i - start;
1576 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1577 reslen += pfield->rm_eo - pfield->rm_so;
1584 memcpy(result + reslen, out + start, i - start);
1585 reslen += i - start;
1586 memcpy(in, result, reslen);
1591 const char *radmsgtype2string(uint8_t code) {
1592 static const char *rad_msg_names[] = {
1593 "", "Access-Request", "Access-Accept", "Access-Reject",
1594 "Accounting-Request", "Accounting-Response", "", "",
1595 "", "", "", "Access-Challenge",
1596 "Status-Server", "Status-Client"
1598 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1601 void char2hex(char *h, unsigned char c) {
1602 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1603 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1604 h[0] = hexdigits[c / 16];
1605 h[1] = hexdigits[c % 16];
1609 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
1613 if (!attr || len == 1) {
1618 l = ATTRVALLEN(attr);
1619 s = (char *)ATTRVAL(attr);
1622 for (i = 0; i < l; i++) {
1623 if (s[i] > 31 && s[i] < 127) {
1625 if (d - ascii == len - 1)
1628 if (d - ascii > len - 4)
1633 if (d - ascii == len - 1)
1641 void acclog(unsigned char *attrs, int length, char *host) {
1642 unsigned char *attr;
1645 attr = attrget(attrs, length, RAD_Attr_User_Name);
1647 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1650 radattr2ascii(username, sizeof(username), attr);
1651 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1654 void respondaccounting(struct request *rq) {
1655 unsigned char *resp;
1659 debug(DBG_ERR, "respondaccounting: malloc failed");
1662 memcpy(resp, rq->buf, 20);
1663 resp[0] = RAD_Accounting_Response;
1666 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1667 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1670 void respondstatusserver(struct request *rq) {
1671 unsigned char *resp;
1675 debug(DBG_ERR, "respondstatusserver: malloc failed");
1678 memcpy(resp, rq->buf, 20);
1679 resp[0] = RAD_Access_Accept;
1682 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1683 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1686 void respondreject(struct request *rq, char *message) {
1687 unsigned char *resp;
1690 if (message && *message)
1691 len += 2 + strlen(message);
1695 debug(DBG_ERR, "respondreject: malloc failed");
1698 memcpy(resp, rq->buf, 20);
1699 resp[0] = RAD_Access_Reject;
1700 *(uint16_t *)(resp + 2) = htons(len);
1701 if (message && *message) {
1702 resp[20] = RAD_Attr_Reply_Message;
1703 resp[21] = len - 20;
1704 memcpy(resp + 22, message, len - 22);
1706 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1709 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1710 struct list_node *entry;
1711 struct clsrvconf *server, *best = NULL, *first = NULL;
1713 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1714 server = (struct clsrvconf *)entry->data;
1715 if (!server->servers)
1719 if (!server->servers->connectionok)
1721 if (!server->servers->lostrqs)
1727 if (server->servers->lostrqs < best->servers->lostrqs)
1730 return best ? best : first;
1733 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
1734 struct clsrvconf *srvconf;
1736 *realm = id2realm(realms, id);
1739 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1740 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1743 if (!acc && !srvconf->servers)
1744 adddynamicrealmserver(*realm, srvconf, id);
1745 return srvconf->servers;
1748 /* returns 0 if validation/authentication fails, else 1 */
1749 int radsrv(struct request *rq) {
1750 uint8_t code, id, *auth, *attrs, *attr;
1752 struct server *to = NULL;
1753 char username[254], userascii[760];
1754 unsigned char newauth[16];
1755 struct realm *realm = NULL;
1757 code = *(uint8_t *)rq->buf;
1758 id = *(uint8_t *)(rq->buf + 1);
1759 len = RADLEN(rq->buf);
1760 auth = (uint8_t *)(rq->buf + 4);
1762 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1764 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1765 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1770 attrs = rq->buf + 20;
1772 if (!attrvalidate(attrs, len)) {
1773 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1777 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1778 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
1779 debug(DBG_WARN, "radsrv: message authentication failed");
1783 if (code == RAD_Status_Server) {
1784 respondstatusserver(rq);
1788 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1790 if (code == RAD_Accounting_Request) {
1791 memset(newauth, 0, 16);
1792 if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
1793 debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
1798 if (rq->from->conf->rewrite) {
1799 dorewrite(rq->buf, rq->from->conf->rewrite);
1800 len = RADLEN(rq->buf) - 20;
1803 attr = attrget(attrs, len, RAD_Attr_User_Name);
1805 if (code == RAD_Accounting_Request) {
1806 acclog(attrs, len, rq->from->conf->host);
1807 respondaccounting(rq);
1809 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1812 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1813 username[ATTRVALLEN(attr)] = '\0';
1814 radattr2ascii(userascii, sizeof(userascii), attr);
1816 if (rq->from->conf->rewriteattrregex) {
1817 if (!rewriteusername(rq, username)) {
1818 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1821 len = RADLEN(rq->buf) - 20;
1822 auth = (uint8_t *)(rq->buf + 4);
1823 attrs = rq->buf + 20;
1826 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
1828 to = findserver(&realm, username, code == RAD_Accounting_Request);
1830 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1834 if (realm->message && code == RAD_Access_Request) {
1835 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
1836 respondreject(rq, realm->message);
1837 } else if (realm->accresp && code == RAD_Accounting_Request) {
1838 acclog(attrs, len, rq->from->conf->host);
1839 respondaccounting(rq);
1844 if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
1845 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
1846 rq->from->conf->name, to->conf->name);
1850 if (rqinqueue(to, rq->from, id, code)) {
1851 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
1852 radmsgtype2string(code), rq->from->conf->host, id);
1856 if (code != RAD_Accounting_Request) {
1857 if (!RAND_bytes(newauth, 16)) {
1858 debug(DBG_WARN, "radsrv: failed to generate random auth");
1864 printfchars(NULL, "auth", "%02x ", auth, 16);
1867 attr = attrget(attrs, len, RAD_Attr_User_Password);
1869 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1870 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
1874 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1876 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1877 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
1882 memcpy(rq->origauth, auth, 16);
1883 memcpy(auth, newauth, 16);
1896 int replyh(struct server *server, unsigned char *buf) {
1897 struct client *from;
1900 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
1901 struct sockaddr_storage fromsa;
1902 char tmp[760], stationid[760];
1904 server->connectionok = 1;
1905 server->lostrqs = 0;
1907 i = buf[1]; /* i is the id */
1909 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
1910 && *buf != RAD_Accounting_Response) {
1911 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
1914 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
1916 rq = server->requests + i;
1918 pthread_mutex_lock(&server->newrq_mutex);
1919 if (!rq->buf || !rq->tries) {
1920 pthread_mutex_unlock(&server->newrq_mutex);
1921 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
1926 pthread_mutex_unlock(&server->newrq_mutex);
1927 debug(DBG_INFO, "replyh: already received, ignoring reply");
1931 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
1932 pthread_mutex_unlock(&server->newrq_mutex);
1933 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
1937 len = RADLEN(buf) - 20;
1940 if (!attrvalidate(attrs, len)) {
1941 pthread_mutex_unlock(&server->newrq_mutex);
1942 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
1946 /* Message Authenticator */
1947 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1949 if (ATTRVALLEN(messageauth) != 16) {
1950 pthread_mutex_unlock(&server->newrq_mutex);
1951 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
1954 memcpy(tmp, buf + 4, 16);
1955 memcpy(buf + 4, rq->buf + 4, 16);
1956 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
1957 pthread_mutex_unlock(&server->newrq_mutex);
1958 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
1961 memcpy(buf + 4, tmp, 16);
1962 debug(DBG_DBG, "replyh: message auth ok");
1965 gettimeofday(&server->lastrcv, NULL);
1967 if (*rq->buf == RAD_Status_Server) {
1969 pthread_mutex_unlock(&server->newrq_mutex);
1970 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
1974 gettimeofday(&server->lastreply, NULL);
1978 pthread_mutex_unlock(&server->newrq_mutex);
1979 debug(DBG_INFO, "replyh: client gone, ignoring reply");
1983 if (server->conf->rewrite) {
1984 dorewrite(buf, server->conf->rewrite);
1985 len = RADLEN(buf) - 20;
1989 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1990 if (ATTRVALLEN(attr) <= 4)
1993 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
1996 sublen = ATTRVALLEN(attr) - 4;
1997 subattrs = ATTRVAL(attr) + 4;
1998 if (!attrvalidate(subattrs, sublen) ||
1999 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2000 rq, server->conf->secret, from->conf->secret) ||
2001 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2002 rq, server->conf->secret, from->conf->secret))
2006 pthread_mutex_unlock(&server->newrq_mutex);
2007 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2011 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2012 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2014 radattr2ascii(tmp, sizeof(tmp), attr);
2015 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2017 radattr2ascii(stationid, sizeof(stationid), attr);
2018 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2019 radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2021 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2025 buf[1] = (char)rq->origid;
2026 memcpy(buf + 4, rq->origauth, 16);
2028 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2031 if (rq->origusername) {
2032 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2034 pthread_mutex_unlock(&server->newrq_mutex);
2035 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2038 memcpy(username, rq->origusername, strlen(rq->origusername));
2039 len = RADLEN(buf) - 20;
2042 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2046 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2047 pthread_mutex_unlock(&server->newrq_mutex);
2048 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2051 debug(DBG_DBG, "replyh: computed messageauthattr");
2054 fromsa = rq->fromsa; /* only needed for UDP */
2055 /* once we set received = 1, rq may be reused */
2058 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2059 sendreply(from, buf, &fromsa, rq->fromudpsock);
2060 pthread_mutex_unlock(&server->newrq_mutex);
2064 /* code for removing state not finished */
2065 void *clientwr(void *arg) {
2066 struct server *server = (struct server *)arg;
2068 pthread_t clientrdth;
2069 int i, dynconffail = 0;
2072 struct timespec timeout;
2073 struct request statsrvrq;
2074 unsigned char statsrvbuf[38];
2075 struct clsrvconf *conf;
2077 conf = server->conf;
2079 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2084 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2085 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2089 memset(&timeout, 0, sizeof(struct timespec));
2091 if (conf->statusserver) {
2092 memset(&statsrvrq, 0, sizeof(struct request));
2093 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2094 statsrvbuf[0] = RAD_Status_Server;
2096 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2097 statsrvbuf[21] = 18;
2098 gettimeofday(&server->lastrcv, NULL);
2101 if (conf->pdef->connecter) {
2102 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2104 server->connectionok = 1;
2105 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
2106 debug(DBG_ERR, "clientwr: pthread_create failed");
2110 server->connectionok = 1;
2113 pthread_mutex_lock(&server->newrq_mutex);
2114 if (!server->newrq) {
2115 gettimeofday(&now, NULL);
2116 /* random 0-7 seconds */
2117 RAND_bytes(&rnd, 1);
2119 if (conf->statusserver) {
2120 if (!timeout.tv_sec || timeout.tv_sec > server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd)
2121 timeout.tv_sec = server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd;
2123 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2124 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2127 if (timeout.tv_sec > now.tv_sec)
2128 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2130 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2133 if (server->newrq) {
2134 debug(DBG_DBG, "clientwr: got new request");
2139 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2141 pthread_mutex_unlock(&server->newrq_mutex);
2143 for (i = 0; i < MAX_REQUESTS; i++) {
2144 if (server->clientrdgone) {
2145 pthread_join(clientrdth, NULL);
2148 pthread_mutex_lock(&server->newrq_mutex);
2149 while (i < MAX_REQUESTS && !server->requests[i].buf)
2151 if (i == MAX_REQUESTS) {
2152 pthread_mutex_unlock(&server->newrq_mutex);
2155 rq = server->requests + i;
2158 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2160 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2162 /* setting this to NULL means that it can be reused */
2165 pthread_mutex_unlock(&server->newrq_mutex);
2169 gettimeofday(&now, NULL);
2170 if (now.tv_sec < rq->expiry.tv_sec) {
2171 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2172 timeout.tv_sec = rq->expiry.tv_sec;
2173 pthread_mutex_unlock(&server->newrq_mutex);
2177 if (rq->tries == (*rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2178 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2179 if (conf->statusserver) {
2180 if (*rq->buf == RAD_Status_Server) {
2181 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2182 if (server->lostrqs < 255)
2186 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2187 if (server->lostrqs < 255)
2191 /* setting this to NULL means that it can be reused */
2193 pthread_mutex_unlock(&server->newrq_mutex);
2196 pthread_mutex_unlock(&server->newrq_mutex);
2198 rq->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2199 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2200 timeout.tv_sec = rq->expiry.tv_sec;
2202 conf->pdef->clientradput(server, server->requests[i].buf);
2204 if (conf->statusserver) {
2205 gettimeofday(&now, NULL);
2206 if (now.tv_sec - server->lastrcv.tv_sec >= STATUS_SERVER_PERIOD) {
2207 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2208 debug(DBG_WARN, "clientwr: failed to generate random auth");
2211 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2212 if (!statsrvrq.buf) {
2213 debug(DBG_ERR, "clientwr: malloc failed");
2216 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2217 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2218 sendrq(server, &statsrvrq);
2223 conf->servers = NULL;
2224 if (server->dynamiclookuparg) {
2225 removeserversubrealms(realms, conf);
2229 freeclsrvconf(conf);
2231 freeserver(server, 1);
2232 ERR_remove_state(0);
2236 void createlistener(uint8_t type, char *arg) {
2238 struct clsrvconf *listenres;
2239 struct addrinfo *res;
2240 int s = -1, on = 1, *sp = NULL;
2242 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2244 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2246 for (res = listenres->addrinfo; res; res = res->ai_next) {
2247 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2249 debug(DBG_WARN, "createlistener: socket failed");
2252 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2254 if (res->ai_family == AF_INET6)
2255 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2257 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2258 debug(DBG_WARN, "createlistener: bind failed");
2264 sp = malloc(sizeof(int));
2266 debugx(1, DBG_ERR, "malloc failed");
2268 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
2269 debugx(1, DBG_ERR, "pthread_create failed");
2273 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2275 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
2276 listenres->host ? listenres->host : "*", listenres->port);
2277 freeclsrvres(listenres);
2280 void createlisteners(uint8_t type, char **args) {
2284 for (i = 0; args[i]; i++)
2285 createlistener(type, args[i]);
2287 createlistener(type, NULL);
2291 void ssl_info_callback(const SSL *ssl, int where, int ret) {
2295 w = where & ~SSL_ST_MASK;
2297 if (w & SSL_ST_CONNECT)
2299 else if (w & SSL_ST_ACCEPT)
2304 if (where & SSL_CB_LOOP)
2305 debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
2306 else if (where & SSL_CB_ALERT) {
2307 s = (where & SSL_CB_READ) ? "read" : "write";
2308 debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
2310 else if (where & SSL_CB_EXIT) {
2312 debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
2314 debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
2319 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2320 SSL_CTX *ctx = NULL;
2321 STACK_OF(X509_NAME) *calist;
2324 unsigned long error;
2327 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2328 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2329 for (i = 0; i < CRYPTO_num_locks(); i++) {
2330 ssl_lock_count[i] = 0;
2331 pthread_mutex_init(&ssl_locks[i], NULL);
2333 CRYPTO_set_id_callback(ssl_thread_id);
2334 CRYPTO_set_locking_callback(ssl_locking_callback);
2336 SSL_load_error_strings();
2339 while (!RAND_status()) {
2340 time_t t = time(NULL);
2341 pid_t pid = getpid();
2342 RAND_seed((unsigned char *)&t, sizeof(time_t));
2343 RAND_seed((unsigned char *)&pid, sizeof(pid));
2349 ctx = SSL_CTX_new(TLSv1_method());
2351 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2355 ctx = SSL_CTX_new(DTLSv1_method());
2357 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2359 SSL_CTX_set_read_ahead(ctx, 1);
2363 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2367 if (conf->certkeypwd) {
2368 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2369 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2371 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2372 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2373 !SSL_CTX_check_private_key(ctx) ||
2374 !SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2375 while ((error = ERR_get_error()))
2376 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2377 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2382 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2383 if (!conf->cacertfile || calist) {
2384 if (conf->cacertpath) {
2386 calist = sk_X509_NAME_new_null();
2387 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2388 sk_X509_NAME_free(calist);
2394 while ((error = ERR_get_error()))
2395 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2396 debug(DBG_ERR, "tlscreatectx: Error adding CA subjects in TLS context %s", conf->name);
2400 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2401 SSL_CTX_set_client_CA_list(ctx, calist);
2403 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2404 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2406 if (conf->crlcheck) {
2407 x509_s = SSL_CTX_get_cert_store(ctx);
2408 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2411 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
2415 SSL_CTX *tlsgetctx(uint8_t type, char *alt1, char *alt2) {
2416 struct list_node *entry;
2417 struct tls *t, *t1 = NULL, *t2 = NULL;
2418 SSL_CTX *ctx = NULL;
2420 pthread_mutex_lock(&tlsconfs_lock);
2422 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2423 t = (struct tls *)entry->data;
2424 if (!strcasecmp(t->name, alt1)) {
2428 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2439 t->tlsctx = tlscreatectx(RAD_TLS, t);
2444 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2450 pthread_mutex_unlock(&tlsconfs_lock);
2454 struct list *addsrvconfs(char *value, char **names) {
2455 struct list *conflist;
2457 struct list_node *entry;
2458 struct clsrvconf *conf = NULL;
2460 if (!names || !*names)
2463 conflist = list_create();
2465 debug(DBG_ERR, "malloc failed");
2469 for (n = 0; names[n]; n++) {
2470 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2471 conf = (struct clsrvconf *)entry->data;
2472 if (!strcasecmp(names[n], conf->name))
2476 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2477 list_destroy(conflist);
2480 if (!list_push(conflist, conf)) {
2481 debug(DBG_ERR, "malloc failed");
2482 list_destroy(conflist);
2485 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2490 void freerealm(struct realm *realm) {
2494 free(realm->message);
2495 regfree(&realm->regex);
2496 pthread_mutex_destroy(&realm->subrealms_mutex);
2497 if (realm->subrealms)
2498 list_destroy(realm->subrealms);
2499 if (realm->srvconfs) {
2500 /* emptying list without freeing data */
2501 while (list_shift(realm->srvconfs));
2502 list_destroy(realm->srvconfs);
2504 if (realm->accsrvconfs) {
2505 /* emptying list without freeing data */
2506 while (list_shift(realm->accsrvconfs));
2507 list_destroy(realm->accsrvconfs);
2512 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2514 struct realm *realm;
2515 char *s, *regex = NULL;
2517 if (*value == '/') {
2518 /* regexp, remove optional trailing / if present */
2519 if (value[strlen(value) - 1] == '/')
2520 value[strlen(value) - 1] = '\0';
2522 /* not a regexp, let us make it one */
2523 if (*value == '*' && !value[1])
2524 regex = stringcopy(".*", 0);
2526 for (n = 0, s = value; *s;)
2529 regex = malloc(strlen(value) + n + 3);
2532 for (n = 1, s = value; *s; s++) {
2542 debug(DBG_ERR, "malloc failed");
2546 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2549 realm = malloc(sizeof(struct realm));
2551 debug(DBG_ERR, "malloc failed");
2554 memset(realm, 0, sizeof(struct realm));
2556 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
2557 debug(DBG_ERR, "mutex init failed");
2563 realm->name = stringcopy(value, 0);
2565 debug(DBG_ERR, "malloc failed");
2568 if (message && strlen(message) > 253) {
2569 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2572 realm->message = message;
2573 realm->accresp = accresp;
2575 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
2576 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2580 if (servers && *servers) {
2581 realm->srvconfs = addsrvconfs(value, servers);
2582 if (!realm->srvconfs)
2586 if (accservers && *accservers) {
2587 realm->accsrvconfs = addsrvconfs(value, accservers);
2588 if (!realm->accsrvconfs)
2592 if (!list_push(realmlist, realm)) {
2593 debug(DBG_ERR, "malloc failed");
2594 pthread_mutex_destroy(&realm->subrealms_mutex);
2598 debug(DBG_DBG, "addrealm: added realm %s", value);
2608 for (n = 0; servers[n]; n++)
2613 for (n = 0; accservers[n]; n++)
2614 free(accservers[n]);
2620 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2621 struct clsrvconf *srvconf;
2622 struct realm *newrealm = NULL;
2623 char *realmname, *s;
2626 if (!conf->dynamiclookupcommand)
2629 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2630 realmname = strrchr(id, '@');
2636 for (s = realmname; *s; s++)
2637 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2640 pthread_mutex_lock(&realm->subrealms_mutex);
2641 /* exit if we now already got a matching subrealm */
2642 if (id2realm(realm->subrealms, id))
2644 srvconf = malloc(sizeof(struct clsrvconf));
2646 debug(DBG_ERR, "malloc failed");
2650 if (!addserver(srvconf))
2653 if (!realm->subrealms)
2654 realm->subrealms = list_create();
2655 if (!realm->subrealms)
2657 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2661 /* add server and accserver to newrealm */
2662 newrealm->srvconfs = list_create();
2663 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2664 debug(DBG_ERR, "malloc failed");
2667 newrealm->accsrvconfs = list_create();
2668 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2669 debug(DBG_ERR, "malloc failed");
2673 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2675 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2676 debug(DBG_ERR, "pthread_create failed");
2679 pthread_detach(clientth);
2684 list_removedata(realm->subrealms, newrealm);
2685 freerealm(newrealm);
2686 if (!list_first(realm->subrealms)) {
2687 list_destroy(realm->subrealms);
2688 realm->subrealms = NULL;
2691 freeserver(srvconf->servers, 1);
2693 debug(DBG_ERR, "failed to create dynamic server");
2696 pthread_mutex_unlock(&realm->subrealms_mutex);
2699 int dynamicconfig(struct server *server) {
2700 int ok, fd[2], status;
2702 struct clsrvconf *conf = server->conf;
2703 struct gconffile *cf = NULL;
2705 /* for now we only learn hostname/address */
2706 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2709 debug(DBG_ERR, "dynamicconfig: pipe error");
2714 debug(DBG_ERR, "dynamicconfig: fork error");
2718 } else if (pid == 0) {
2721 if (fd[1] != STDOUT_FILENO) {
2722 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2723 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2726 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2727 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2731 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2732 ok = getgenericconfig(&cf, NULL,
2733 "Server", CONF_CBK, confserver_cb, (void *)conf,
2738 if (waitpid(pid, &status, 0) < 0) {
2739 debug(DBG_ERR, "dynamicconfig: wait error");
2744 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2752 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2756 int addmatchcertattr(struct clsrvconf *conf) {
2760 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2761 r = &conf->certcnregex;
2762 v = conf->matchcertattr + 4;
2763 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2764 r = &conf->certuriregex;
2765 v = conf->matchcertattr + 20;
2770 /* regexp, remove optional trailing / if present */
2771 if (v[strlen(v) - 1] == '/')
2772 v[strlen(v) - 1] = '\0';
2776 *r = malloc(sizeof(regex_t));
2778 debug(DBG_ERR, "malloc failed");
2781 if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
2784 debug(DBG_ERR, "failed to compile regular expression %s", v);
2790 int addrewriteattr(struct clsrvconf *conf) {
2793 v = conf->rewriteattr + 11;
2794 if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
2796 /* regexp, remove optional trailing / if present */
2797 if (v[strlen(v) - 1] == '/')
2798 v[strlen(v) - 1] = '\0';
2806 conf->rewriteattrregex = malloc(sizeof(regex_t));
2807 if (!conf->rewriteattrregex) {
2808 debug(DBG_ERR, "malloc failed");
2812 conf->rewriteattrreplacement = stringcopy(w, 0);
2813 if (!conf->rewriteattrreplacement) {
2814 free(conf->rewriteattrregex);
2815 conf->rewriteattrregex = NULL;
2819 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
2820 free(conf->rewriteattrregex);
2821 conf->rewriteattrregex = NULL;
2822 free(conf->rewriteattrreplacement);
2823 conf->rewriteattrreplacement = NULL;
2824 debug(DBG_ERR, "failed to compile regular expression %s", v);
2831 /* should accept both names and numeric values, only numeric right now */
2832 uint8_t attrname2val(char *attrname) {
2835 val = atoi(attrname);
2836 return val > 0 && val < 256 ? val : 0;
2839 /* should accept both names and numeric values, only numeric right now */
2840 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2843 *vendor = atoi(attrname);
2844 s = strchr(attrname, ':');
2849 *type = atoi(s + 1);
2850 return *type >= 0 && *type < 256;
2853 struct rewrite *getrewrite(char *alt1, char *alt2) {
2854 struct list_node *entry;
2855 struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
2857 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
2858 r = (struct rewriteconf *)entry->data;
2859 if (!strcasecmp(r->name, alt1)) {
2863 if (!r2 && alt2 && !strcasecmp(r->name, alt2))
2873 void addrewrite(char *value, char **attrs, char **vattrs) {
2874 struct rewriteconf *new;
2875 struct rewrite *rewrite = NULL;
2878 uint32_t *p, *va = NULL;
2882 for (; attrs[n]; n++);
2883 a = malloc((n + 1) * sizeof(uint8_t));
2885 debugx(1, DBG_ERR, "malloc failed");
2887 for (i = 0; i < n; i++) {
2888 if (!(a[i] = attrname2val(attrs[i])))
2889 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
2898 for (; vattrs[n]; n++);
2899 va = malloc((2 * n + 1) * sizeof(uint32_t));
2901 debugx(1, DBG_ERR, "malloc failed");
2903 for (p = va, i = 0; i < n; i++, p += 2) {
2904 if (!vattrname2val(vattrs[i], p, p + 1))
2905 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
2913 rewrite = malloc(sizeof(struct rewrite));
2915 debugx(1, DBG_ERR, "malloc failed");
2916 rewrite->removeattrs = a;
2917 rewrite->removevendorattrs = va;
2920 new = malloc(sizeof(struct rewriteconf));
2921 if (!new || !list_push(rewriteconfs, new))
2922 debugx(1, DBG_ERR, "malloc failed");
2924 memset(new, 0, sizeof(struct rewriteconf));
2925 new->name = stringcopy(value, 0);
2927 debugx(1, DBG_ERR, "malloc failed");
2929 new->rewrite = rewrite;
2930 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2933 void freeclsrvconf(struct clsrvconf *conf) {
2939 free(conf->matchcertattr);
2940 if (conf->certcnregex)
2941 regfree(conf->certcnregex);
2942 if (conf->certuriregex)
2943 regfree(conf->certuriregex);
2944 free(conf->confrewrite);
2945 free(conf->rewriteattr);
2946 if (conf->rewriteattrregex)
2947 regfree(conf->rewriteattrregex);
2948 free(conf->rewriteattrreplacement);
2949 free(conf->dynamiclookupcommand);
2950 free(conf->rewrite);
2952 freeaddrinfo(conf->addrinfo);
2953 /* not touching ssl_ctx, clients and servers */
2957 int mergeconfstring(char **dst, char **src) {
2966 t = stringcopy(*dst, 0);
2968 debug(DBG_ERR, "malloc failed");
2976 /* assumes dst is a shallow copy */
2977 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2978 if (!mergeconfstring(&dst->name, &src->name) ||
2979 !mergeconfstring(&dst->host, &src->host) ||
2980 !mergeconfstring(&dst->port, &src->port) ||
2981 !mergeconfstring(&dst->secret, &src->secret) ||
2982 !mergeconfstring(&dst->tls, &src->tls) ||
2983 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2984 !mergeconfstring(&dst->confrewrite, &src->confrewrite) ||
2985 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
2988 dst->pdef = src->pdef;
2989 dst->statusserver = src->statusserver;
2990 dst->certnamecheck = src->certnamecheck;
2991 if (src->retryinterval != 255)
2992 dst->retryinterval = src->retryinterval;
2993 if (src->retrycount != 255)
2994 dst->retrycount = src->retrycount;
2998 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2999 struct clsrvconf *conf;
3000 char *conftype = NULL;
3002 debug(DBG_DBG, "confclient_cb called for %s", block);
3004 conf = malloc(sizeof(struct clsrvconf));
3005 if (!conf || !list_push(clconfs, conf))
3006 debugx(1, DBG_ERR, "malloc failed");
3007 memset(conf, 0, sizeof(struct clsrvconf));
3008 conf->certnamecheck = 1;
3010 if (!getgenericconfig(cf, block,
3011 "type", CONF_STR, &conftype,
3012 "host", CONF_STR, &conf->host,
3013 "secret", CONF_STR, &conf->secret,
3014 "tls", CONF_STR, &conf->tls,
3015 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3016 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3017 "rewrite", CONF_STR, &conf->confrewrite,
3018 "rewriteattribute", CONF_STR, &conf->rewriteattr,
3021 debugx(1, DBG_ERR, "configuration error");
3023 conf->name = stringcopy(val, 0);
3025 conf->host = stringcopy(val, 0);
3026 if (!conf->name || !conf->host)
3027 debugx(1, DBG_ERR, "malloc failed");
3030 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3031 conf->type = protoname2int(conftype);
3032 conf->pdef = &protodefs[conf->type];
3033 if (!conf->pdef->name)
3034 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3037 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3038 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultclient", "default");
3040 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3041 if (conf->matchcertattr && !addmatchcertattr(conf))
3042 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3045 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
3047 if (conf->rewriteattr) {
3048 if (!addrewriteattr(conf))
3049 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3052 if (!resolvepeer(conf, 0))
3053 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3055 if (!conf->secret) {
3056 if (!conf->pdef->secretdefault)
3057 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3058 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3060 debugx(1, DBG_ERR, "malloc failed");
3065 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3066 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3067 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultserver", "default");
3068 if (!conf->ssl_ctx) {
3069 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3072 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3073 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3079 conf->port = stringcopy(conf->pdef->portdefault, 0);
3081 debug(DBG_ERR, "malloc failed");
3086 if (conf->retryinterval == 255)
3087 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3088 if (conf->retrycount == 255)
3089 conf->retrycount = protodefs[conf->type].retrycountdefault;
3091 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
3093 if (!conf->secret) {
3094 if (!conf->pdef->secretdefault) {
3095 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3098 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3099 if (!conf->secret) {
3100 debug(DBG_ERR, "malloc failed");
3105 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3106 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3112 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3113 struct clsrvconf *conf, *resconf;
3114 char *conftype = NULL;
3115 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3117 debug(DBG_DBG, "confserver_cb called for %s", block);
3119 conf = malloc(sizeof(struct clsrvconf));
3121 debug(DBG_ERR, "malloc failed");
3124 memset(conf, 0, sizeof(struct clsrvconf));
3125 resconf = (struct clsrvconf *)arg;
3127 conf->statusserver = resconf->statusserver;
3128 conf->certnamecheck = resconf->certnamecheck;
3130 conf->certnamecheck = 1;
3132 if (!getgenericconfig(cf, block,
3133 "type", CONF_STR, &conftype,
3134 "host", CONF_STR, &conf->host,
3135 "port", CONF_STR, &conf->port,
3136 "secret", CONF_STR, &conf->secret,
3137 "tls", CONF_STR, &conf->tls,
3138 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3139 "rewrite", CONF_STR, &conf->confrewrite,
3140 "StatusServer", CONF_BLN, &conf->statusserver,
3141 "RetryInterval", CONF_LINT, &retryinterval,
3142 "RetryCount", CONF_LINT, &retrycount,
3143 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3144 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3147 debug(DBG_ERR, "configuration error");
3151 conf->name = stringcopy(val, 0);
3153 debug(DBG_ERR, "malloc failed");
3157 conf->host = stringcopy(val, 0);
3159 debug(DBG_ERR, "malloc failed");
3165 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3166 conf->type = protoname2int(conftype);
3167 conf->pdef = &protodefs[conf->type];
3168 if (!conf->pdef->name) {
3169 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3175 if (retryinterval != LONG_MIN) {
3176 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3177 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3180 conf->retryinterval = (uint8_t)retryinterval;
3182 conf->retryinterval = 255;
3184 if (retrycount != LONG_MIN) {
3185 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3186 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3189 conf->retrycount = (uint8_t)retrycount;
3191 conf->retrycount = 255;
3194 if (!mergesrvconf(resconf, conf))
3198 if (conf->dynamiclookupcommand) {
3199 free(conf->dynamiclookupcommand);
3200 conf->dynamiclookupcommand = NULL;
3204 if (resconf || !conf->dynamiclookupcommand) {
3205 if (!compileserverconfig(conf, block))
3212 if (!list_push(srvconfs, conf)) {
3213 debug(DBG_ERR, "malloc failed");
3219 freeclsrvconf(conf);
3223 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3224 char **servers = NULL, **accservers = NULL, *msg = NULL;
3225 uint8_t accresp = 0;
3227 debug(DBG_DBG, "confrealm_cb called for %s", block);
3229 if (!getgenericconfig(cf, block,
3230 "server", CONF_MSTR, &servers,
3231 "accountingServer", CONF_MSTR, &accservers,
3232 "ReplyMessage", CONF_STR, &msg,
3233 "AccountingResponse", CONF_BLN, &accresp,
3236 debugx(1, DBG_ERR, "configuration error");
3238 addrealm(realms, val, servers, accservers, msg, accresp);
3242 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3245 debug(DBG_DBG, "conftls_cb called for %s", block);
3247 conf = malloc(sizeof(struct tls));
3249 debug(DBG_ERR, "conftls_cb: malloc failed");
3252 memset(conf, 0, sizeof(struct tls));
3254 if (!getgenericconfig(cf, block,
3255 "CACertificateFile", CONF_STR, &conf->cacertfile,
3256 "CACertificatePath", CONF_STR, &conf->cacertpath,
3257 "CertificateFile", CONF_STR, &conf->certfile,
3258 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3259 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3260 "CRLCheck", CONF_BLN, &conf->crlcheck,
3263 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3266 if (!conf->certfile || !conf->certkeyfile) {
3267 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3270 if (!conf->cacertfile && !conf->cacertpath) {
3271 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3275 conf->name = stringcopy(val, 0);
3277 debug(DBG_ERR, "conftls_cb: malloc failed");
3281 pthread_mutex_lock(&tlsconfs_lock);
3282 if (!list_push(tlsconfs, conf)) {
3283 debug(DBG_ERR, "conftls_cb: malloc failed");
3284 pthread_mutex_unlock(&tlsconfs_lock);
3287 pthread_mutex_unlock(&tlsconfs_lock);
3289 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3293 free(conf->cacertfile);
3294 free(conf->cacertpath);
3295 free(conf->certfile);
3296 free(conf->certkeyfile);
3297 free(conf->certkeypwd);
3302 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3303 char **attrs = NULL, **vattrs = NULL;
3305 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3307 if (!getgenericconfig(cf, block,
3308 "removeAttribute", CONF_MSTR, &attrs,
3309 "removeVendorAttribute", CONF_MSTR, &vattrs,
3312 debugx(1, DBG_ERR, "configuration error");
3313 addrewrite(val, attrs, vattrs);
3317 void getmainconfig(const char *configfile) {
3318 long int loglevel = LONG_MIN;
3319 struct gconffile *cfs;
3321 cfs = openconfigfile(configfile);
3322 memset(&options, 0, sizeof(options));
3324 clconfs = list_create();
3326 debugx(1, DBG_ERR, "malloc failed");
3328 srvconfs = list_create();
3330 debugx(1, DBG_ERR, "malloc failed");
3332 realms = list_create();
3334 debugx(1, DBG_ERR, "malloc failed");
3336 tlsconfs = list_create();
3338 debugx(1, DBG_ERR, "malloc failed");
3340 rewriteconfs = list_create();
3342 debugx(1, DBG_ERR, "malloc failed");
3344 if (!getgenericconfig(&cfs, NULL,
3345 "ListenUDP", CONF_MSTR, &options.listenudp,
3346 "ListenTCP", CONF_MSTR, &options.listentcp,
3347 "ListenTLS", CONF_MSTR, &options.listentls,
3348 "ListenDTLS", CONF_MSTR, &options.listendtls,
3349 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
3350 "SourceUDP", CONF_STR, &options.sourceudp,
3351 "SourceTCP", CONF_STR, &options.sourcetcp,
3352 "SourceTLS", CONF_STR, &options.sourcetls,
3353 "SourceDTLS", CONF_STR, &options.sourcedtls,
3354 "LogLevel", CONF_LINT, &loglevel,
3355 "LogDestination", CONF_STR, &options.logdestination,
3356 "LoopPrevention", CONF_BLN, &options.loopprevention,
3357 "Client", CONF_CBK, confclient_cb, NULL,
3358 "Server", CONF_CBK, confserver_cb, NULL,
3359 "Realm", CONF_CBK, confrealm_cb, NULL,
3360 "TLS", CONF_CBK, conftls_cb, NULL,
3361 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3364 debugx(1, DBG_ERR, "configuration error");
3366 if (loglevel != LONG_MIN) {
3367 if (loglevel < 1 || loglevel > 4)
3368 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3369 options.loglevel = (uint8_t)loglevel;
3373 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3376 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3379 *configfile = optarg;
3382 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3383 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3384 *loglevel = *optarg - '0';
3393 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3398 if (!(argc - optind))
3402 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3406 int daemon(int a, int b) {
3414 for (i = 0; i < 3; i++) {
3416 open("/dev/null", O_RDWR);
3422 void *sighandler(void *arg) {
3427 sigemptyset(&sigset);
3428 sigaddset(&sigset, SIGPIPE);
3429 sigwait(&sigset, &sig);
3430 /* only get SIGPIPE right now, so could simplify below code */
3433 /* completely ignoring this */
3436 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3439 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3444 int main(int argc, char **argv) {
3447 struct list_node *entry;
3448 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3449 char *configfile = NULL;
3450 struct clsrvconf *srvconf;
3453 debug_init("radsecproxy");
3454 debug_set_level(DEBUG_LEVEL);
3455 pthread_mutex_init(&tlsconfs_lock, NULL);
3457 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3459 debug_set_level(loglevel);
3460 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3462 options.loglevel = loglevel;
3463 else if (options.loglevel)
3464 debug_set_level(options.loglevel);
3466 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3467 free(options.logdestination);
3469 if (!list_first(clconfs))
3470 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3471 if (!list_first(realms))
3472 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3475 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3477 if (!foreground && (daemon(0, 0) < 0))
3478 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3480 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3482 sigemptyset(&sigset);
3483 /* exit on all but SIGPIPE, ignore more? */
3484 sigaddset(&sigset, SIGPIPE);
3485 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3486 pthread_create(&sigth, NULL, sighandler, NULL);
3488 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3489 srvconf = (struct clsrvconf *)entry->data;
3490 if (srvconf->dynamiclookupcommand)
3492 if (!addserver(srvconf))
3493 debugx(1, DBG_ERR, "failed to add server");
3494 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3495 (void *)(srvconf->servers)))
3496 debugx(1, DBG_ERR, "pthread_create failed");
3498 /* srcprotores for UDP no longer needed */
3499 if (srcprotores[RAD_UDP]) {
3500 freeaddrinfo(srcprotores[RAD_UDP]);
3501 srcprotores[RAD_UDP] = NULL;
3504 for (i = 0; protodefs[i].name; i++)
3505 if (protodefs[i].initextra)
3506 protodefs[i].initextra();
3508 if (find_clconf_type(RAD_TCP, NULL))
3509 createlisteners(RAD_TCP, options.listentcp);
3511 if (find_clconf_type(RAD_TLS, NULL))
3512 createlisteners(RAD_TLS, options.listentls);
3514 if (find_clconf_type(RAD_DTLS, NULL))
3515 createlisteners(RAD_DTLS, options.listendtls);
3517 if (find_clconf_type(RAD_UDP, NULL)) {
3518 createlisteners(RAD_UDP, options.listenudp);
3519 if (options.listenaccudp)
3520 createlisteners(RAD_UDP, options.listenaccudp);
3523 /* just hang around doing nothing, anything to do here? */