2 * Copyright (C) 2006-2008 Stig Venaas <venaas@uninett.no>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
9 /* Code contributions from:
11 * Arne Schwabe <schwabe at uni-paderborn.de>
14 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
15 * rd is responsible for init and launching wr
16 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
17 * each tlsserverrd launches tlsserverwr
18 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
19 * for init and launching rd
21 * serverrd will receive a request, processes it and puts it in the requestq of
22 * the appropriate clientwr
23 * clientwr monitors its requestq and sends requests
24 * clientrd looks for responses, processes them and puts them in the replyq of
25 * the peer the request came from
26 * serverwr monitors its reply and sends replies
28 * In addition to the main thread, we have:
29 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
30 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
31 * For each TLS peer connecting to us there will be 2 more TLS threads
32 * This is only for connected peers
33 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
34 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
38 * May segfault when dtls connections go down? More testing needed
39 * Remove expired stuff from clients request list?
40 * Multiple outgoing connections if not enough IDs? (multiple servers per conf?)
41 * Useful for TCP accounting? Now we require separate server config for alt port
45 #include <sys/socket.h>
46 #include <netinet/in.h>
55 #include <sys/types.h>
56 #include <sys/select.h>
59 #include <arpa/inet.h>
63 #include <openssl/ssl.h>
64 #include <openssl/rand.h>
65 #include <openssl/err.h>
66 #include <openssl/md5.h>
67 #include <openssl/hmac.h>
68 #include <openssl/x509v3.h>
74 #include "radsecproxy.h"
80 static struct options options;
81 static struct list *clconfs, *srvconfs;
83 struct hash *tlsconfs, *rewriteconfs;
85 static struct addrinfo *srcprotores[RAD_PROTOCOUNT];
87 static pthread_mutex_t *ssl_locks = NULL;
88 static long *ssl_lock_count;
92 /* minimum required declarations to avoid reordering code */
93 struct realm *adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
94 int dynamicconfig(struct server *server);
95 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
96 void freerealm(struct realm *realm);
97 void freeclsrvconf(struct clsrvconf *conf);
98 void freerq(struct request *rq);
99 void freerqoutdata(struct rqout *rqout);
100 void rmclientrq(struct request *rq, uint8_t id);
102 static const struct protodefs protodefs[] = {
103 { "udp", /* UDP, assuming RAD_UDP defined as 0 */
104 NULL, /* secretdefault */
105 SOCK_DGRAM, /* socktype */
106 "1812", /* portdefault */
107 REQUEST_RETRY_COUNT, /* retrycountdefault */
108 10, /* retrycountmax */
109 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
110 60, /* retryintervalmax */
111 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
112 udpserverrd, /* listener */
113 NULL, /* connecter */
114 NULL, /* clientconnreader */
115 clientradputudp, /* clientradput */
116 addclientudp, /* addclient */
117 addserverextraudp, /* addserverextra */
118 1, /* freesrcprotores */
119 initextraudp /* initextra */
121 { "tls", /* TLS, assuming RAD_TLS defined as 1 */
122 "mysecret", /* secretdefault */
123 SOCK_STREAM, /* socktype */
124 "2083", /* portdefault */
125 0, /* retrycountdefault */
126 0, /* retrycountmax */
127 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
128 60, /* retryintervalmax */
129 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
130 tlslistener, /* listener */
131 tlsconnect, /* connecter */
132 tlsclientrd, /* clientconnreader */
133 clientradputtls, /* clientradput */
134 NULL, /* addclient */
135 NULL, /* addserverextra */
136 0, /* freesrcprotores */
139 { "tcp", /* TCP, assuming RAD_TCP defined as 2 */
140 NULL, /* secretdefault */
141 SOCK_STREAM, /* socktype */
142 "1812", /* portdefault */
143 0, /* retrycountdefault */
144 0, /* retrycountmax */
145 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
146 60, /* retryintervalmax */
147 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
148 tcplistener, /* listener */
149 tcpconnect, /* connecter */
150 tcpclientrd, /* clientconnreader */
151 clientradputtcp, /* clientradput */
152 NULL, /* addclient */
153 NULL, /* addserverextra */
154 0, /* freesrcprotores */
157 { "dtls", /* DTLS, assuming RAD_DTLS defined as 3 */
158 "mysecret", /* secretdefault */
159 SOCK_DGRAM, /* socktype */
160 "2083", /* portdefault */
161 REQUEST_RETRY_COUNT, /* retrycountdefault */
162 10, /* retrycountmax */
163 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
164 60, /* retryintervalmax */
165 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
166 udpdtlsserverrd, /* listener */
167 dtlsconnect, /* connecter */
168 dtlsclientrd, /* clientconnreader */
169 clientradputdtls, /* clientradput */
170 NULL, /* addclient */
171 addserverextradtls, /* addserverextra */
172 1, /* freesrcprotores */
173 initextradtls /* initextra */
175 { NULL, NULL, 0, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL
179 uint8_t protoname2int(const char *name) {
182 for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
186 /* callbacks for making OpenSSL thread safe */
187 unsigned long ssl_thread_id() {
188 return (unsigned long)pthread_self();
191 void ssl_locking_callback(int mode, int type, const char *file, int line) {
192 if (mode & CRYPTO_LOCK) {
193 pthread_mutex_lock(&ssl_locks[type]);
194 ssl_lock_count[type]++;
196 pthread_mutex_unlock(&ssl_locks[type]);
199 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
200 int pwdlen = strlen(userdata);
201 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
203 memcpy(buf, userdata, pwdlen);
207 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
212 err_cert = X509_STORE_CTX_get_current_cert(ctx);
213 err = X509_STORE_CTX_get_error(ctx);
214 depth = X509_STORE_CTX_get_error_depth(ctx);
216 if (depth > MAX_CERT_DEPTH) {
218 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
219 X509_STORE_CTX_set_error(ctx, err);
224 buf = X509_NAME_oneline(X509_get_subject_name(err_cert), NULL, 0);
225 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf ? buf : "");
230 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
232 buf = X509_NAME_oneline(X509_get_issuer_name(err_cert), NULL, 0);
234 debug(DBG_WARN, "\tIssuer=%s", buf);
240 case X509_V_ERR_CERT_NOT_YET_VALID:
241 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
242 debug(DBG_WARN, "\tCertificate not yet valid");
244 case X509_V_ERR_CERT_HAS_EXPIRED:
245 debug(DBG_WARN, "Certificate has expired");
247 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
248 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
250 case X509_V_ERR_NO_EXPLICIT_POLICY:
251 debug(DBG_WARN, "No Explicit Certificate Policy");
256 printf("certificate verify returns %d\n", ok);
261 struct addrinfo *getsrcprotores(uint8_t type) {
262 return srcprotores[type];
265 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
266 struct addrinfo hints, *addrinfo, *res;
270 slash = conf->host ? strchr(conf->host, '/') : NULL;
274 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
278 if (*s < '0' || *s > '9') {
279 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
282 plen = atoi(slash + 1);
283 if (plen < 0 || plen > 128) {
284 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
289 memset(&hints, 0, sizeof(hints));
290 hints.ai_socktype = conf->pdef->socktype;
291 hints.ai_family = AF_UNSPEC;
292 hints.ai_flags = ai_flags;
293 if (!conf->host && !conf->port) {
294 /* getaddrinfo() doesn't like host and port to be NULL */
295 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
296 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
299 for (res = addrinfo; res; res = res->ai_next)
300 port_set(res->ai_addr, 0);
303 hints.ai_flags |= AI_NUMERICHOST;
304 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
305 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
310 switch (addrinfo->ai_family) {
313 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
314 freeaddrinfo(addrinfo);
321 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
322 freeaddrinfo(addrinfo);
325 conf->prefixlen = (uint8_t)plen;
327 conf->prefixlen = 255;
330 freeaddrinfo(conf->addrinfo);
331 conf->addrinfo = addrinfo;
335 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
340 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
344 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
346 debugx(1, DBG_ERR, "no ] matching initial [");
350 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
353 debugx(1, DBG_ERR, "missing host/address");
355 conf->host = stringcopy(field, p - field);
358 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
359 debugx(1, DBG_ERR, "unexpected character after ]");
362 /* port number or service name is specified */;
364 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
366 debugx(1, DBG_ERR, "syntax error, : but no following port");
367 conf->port = stringcopy(field, p - field);
369 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
373 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
374 struct clsrvconf *conf;
376 conf = malloc(sizeof(struct clsrvconf));
378 debugx(1, DBG_ERR, "malloc failed");
379 memset(conf, 0, sizeof(struct clsrvconf));
381 conf->pdef = &protodefs[conf->type];
383 parsehostport(lconf, conf, default_port);
384 if (!strcmp(conf->host, "*")) {
389 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
390 if (!resolvepeer(conf, AI_PASSIVE))
391 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
395 void freeclsrvres(struct clsrvconf *res) {
399 freeaddrinfo(res->addrinfo);
403 /* returns 1 if the len first bits are equal, else 0 */
404 int prefixmatch(void *a1, void *a2, uint8_t len) {
405 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
406 uint8_t r, l = len / 8;
407 if (l && memcmp(a1, a2, l))
412 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
415 /* returns next config with matching address, or NULL */
416 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
417 struct sockaddr_in6 *sa6 = NULL;
418 struct in_addr *a4 = NULL;
419 struct addrinfo *res;
420 struct list_node *entry;
421 struct clsrvconf *conf;
423 if (addr->sa_family == AF_INET6) {
424 sa6 = (struct sockaddr_in6 *)addr;
425 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
426 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
430 a4 = &((struct sockaddr_in *)addr)->sin_addr;
432 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
433 conf = (struct clsrvconf *)entry->data;
434 if (conf->type == type) {
435 if (conf->prefixlen == 255) {
436 for (res = conf->addrinfo; res; res = res->ai_next)
437 if ((a4 && res->ai_family == AF_INET &&
438 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
439 (sa6 && res->ai_family == AF_INET6 &&
440 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
446 res = conf->addrinfo;
448 ((a4 && res->ai_family == AF_INET &&
449 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
450 (sa6 && res->ai_family == AF_INET6 &&
451 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
462 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
463 return find_conf(type, addr, clconfs, cur);
466 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
467 return find_conf(type, addr, srvconfs, cur);
470 /* returns next config of given type, or NULL */
471 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
472 struct list_node *entry;
473 struct clsrvconf *conf;
475 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
476 conf = (struct clsrvconf *)entry->data;
477 if (conf->type == type) {
486 struct queue *newqueue() {
489 q = malloc(sizeof(struct queue));
491 debugx(1, DBG_ERR, "malloc failed");
492 q->entries = list_create();
494 debugx(1, DBG_ERR, "malloc failed");
495 pthread_mutex_init(&q->mutex, NULL);
496 pthread_cond_init(&q->cond, NULL);
500 void removequeue(struct queue *q) {
501 struct list_node *entry;
505 pthread_mutex_lock(&q->mutex);
506 for (entry = list_first(q->entries); entry; entry = list_next(entry))
507 freerq((struct request *)entry);
508 list_destroy(q->entries);
509 pthread_cond_destroy(&q->cond);
510 pthread_mutex_unlock(&q->mutex);
511 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, uint8_t lock) {
526 struct client *new = malloc(sizeof(struct client));
529 debug(DBG_ERR, "malloc failed");
534 pthread_mutex_lock(conf->lock);
535 if (!conf->clients) {
536 conf->clients = list_create();
537 if (!conf->clients) {
539 pthread_mutex_unlock(conf->lock);
540 debug(DBG_ERR, "malloc failed");
545 memset(new, 0, sizeof(struct client));
547 if (conf->pdef->addclient)
548 conf->pdef->addclient(new);
550 new->replyq = newqueue();
551 list_push(conf->clients, new);
553 pthread_mutex_unlock(conf->lock);
557 void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
558 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
561 pthread_mutex_lock(&lock);
563 pthread_mutex_unlock(&lock);
566 void removeclientrqs(struct client *client) {
571 removeclientrqs_sendrq_freeserver_lock(1);
572 for (i = 0; i < MAX_REQUESTS; i++) {
577 rqout = rq->to->requests + rq->newid;
578 pthread_mutex_lock(rqout->lock);
579 if (rqout->rq == rq) /* still pointing to our request */
580 freerqoutdata(rqout);
581 pthread_mutex_unlock(rqout->lock);
585 removeclientrqs_sendrq_freeserver_lock(0);
588 void removelockedclient(struct client *client) {
589 struct clsrvconf *conf;
593 removeclientrqs(client);
594 removequeue(client->replyq);
595 list_removedata(conf->clients, client);
601 void removeclient(struct client *client) {
602 struct clsrvconf *conf;
608 pthread_mutex_lock(conf->lock);
609 removelockedclient(client);
610 pthread_mutex_unlock(conf->lock);
613 void freeserver(struct server *server, uint8_t destroymutex) {
614 struct rqout *rqout, *end;
619 removeclientrqs_sendrq_freeserver_lock(1);
620 if (server->requests) {
621 rqout = server->requests;
622 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
624 rqout->rq->to = NULL;
625 freerqoutdata(rqout);
626 pthread_mutex_destroy(rqout->lock);
629 free(server->requests);
632 freebios(server->rbios);
633 free(server->dynamiclookuparg);
635 SSL_free(server->ssl);
637 pthread_mutex_destroy(&server->lock);
638 pthread_cond_destroy(&server->newrq_cond);
639 pthread_mutex_destroy(&server->newrq_mutex);
641 removeclientrqs_sendrq_freeserver_lock(0);
645 int addserver(struct clsrvconf *conf) {
646 struct clsrvconf *res;
651 debug(DBG_ERR, "addserver: currently works with just one server per conf");
654 conf->servers = malloc(sizeof(struct server));
655 if (!conf->servers) {
656 debug(DBG_ERR, "malloc failed");
659 memset(conf->servers, 0, sizeof(struct server));
660 conf->servers->conf = conf;
663 if (type == RAD_DTLS)
664 conf->servers->rbios = newqueue();
666 if (!srcprotores[type]) {
667 res = resolve_hostport(type, options.sourcearg[type], NULL);
668 srcprotores[type] = res->addrinfo;
669 res->addrinfo = NULL;
673 conf->servers->sock = -1;
674 if (conf->pdef->addserverextra)
675 conf->pdef->addserverextra(conf);
677 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
678 if (!conf->servers->requests) {
679 debug(DBG_ERR, "malloc failed");
682 for (i = 0; i < MAX_REQUESTS; i++) {
683 conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
684 if (!conf->servers->requests[i].lock) {
685 debug(DBG_ERR, "malloc failed");
688 if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
689 debug(DBG_ERR, "mutex init failed");
690 free(conf->servers->requests[i].lock);
691 conf->servers->requests[i].lock = NULL;
695 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
696 debug(DBG_ERR, "mutex init failed");
699 conf->servers->newrq = 0;
700 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
701 debug(DBG_ERR, "mutex init failed");
702 pthread_mutex_destroy(&conf->servers->lock);
705 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
706 debug(DBG_ERR, "mutex init failed");
707 pthread_mutex_destroy(&conf->servers->newrq_mutex);
708 pthread_mutex_destroy(&conf->servers->lock);
715 freeserver(conf->servers, 0);
716 conf->servers = NULL;
720 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
721 int loc, i, l, n, r = 0;
724 STACK_OF(GENERAL_NAME) *alt;
727 debug(DBG_DBG, "subjectaltnameaddr");
729 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
733 ex = X509_get_ext(cert, loc);
734 alt = X509V3_EXT_d2i(ex);
738 n = sk_GENERAL_NAME_num(alt);
739 for (i = 0; i < n; i++) {
740 gn = sk_GENERAL_NAME_value(alt, i);
741 if (gn->type != GEN_IPADD)
744 v = (char *)ASN1_STRING_data(gn->d.ia5);
745 l = ASN1_STRING_length(gn->d.ia5);
746 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
747 && !memcmp(v, &addr, l)) {
752 GENERAL_NAMES_free(alt);
756 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
763 nm = X509_get_subject_name(cert);
766 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
769 e = X509_NAME_get_entry(nm, loc);
770 t = X509_NAME_ENTRY_get_data(e);
771 v = (char *) ASN1_STRING_data(t);
772 l = ASN1_STRING_length(t);
776 if (l == strlen(exact) && !strncasecmp(exact, v, l))
779 s = stringcopy((char *)v, l);
781 debug(DBG_ERR, "malloc failed");
784 if (regexec(regex, s, 0, NULL, 0)) {
795 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
796 int loc, i, l, n, r = 0;
799 STACK_OF(GENERAL_NAME) *alt;
802 debug(DBG_DBG, "subjectaltnameregexp");
804 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
808 ex = X509_get_ext(cert, loc);
809 alt = X509V3_EXT_d2i(ex);
813 n = sk_GENERAL_NAME_num(alt);
814 for (i = 0; i < n; i++) {
815 gn = sk_GENERAL_NAME_value(alt, i);
816 if (gn->type != type)
819 v = (char *)ASN1_STRING_data(gn->d.ia5);
820 l = ASN1_STRING_length(gn->d.ia5);
824 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
827 if (memcmp(v, exact, l))
830 s = stringcopy((char *)v, l);
832 debug(DBG_ERR, "malloc failed");
835 if (regexec(regex, s, 0, NULL, 0)) {
844 GENERAL_NAMES_free(alt);
848 X509 *verifytlscert(SSL *ssl) {
852 if (SSL_get_verify_result(ssl) != X509_V_OK) {
853 debug(DBG_ERR, "verifytlscert: basic validation failed");
854 while ((error = ERR_get_error()))
855 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
859 cert = SSL_get_peer_certificate(ssl);
861 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
865 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
867 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
868 struct in6_addr addr;
870 if (conf->certnamecheck && conf->prefixlen == 255) {
871 if (inet_pton(AF_INET, conf->host, &addr))
873 else if (inet_pton(AF_INET6, conf->host, &addr))
876 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
879 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
882 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
884 if (!cnregexp(cert, conf->host, NULL)) {
885 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
888 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
891 if (conf->certcnregex) {
892 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
893 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
896 debug(DBG_DBG, "verifyconfcert: CN matching regex");
898 if (conf->certuriregex) {
899 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
900 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
903 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
908 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
910 if (ATTRTYPE(attrs) == type)
912 length -= ATTRLEN(attrs);
913 attrs += ATTRLEN(attrs);
918 struct request *newrqref(struct request *rq) {
924 void freerq(struct request *rq) {
927 debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
930 if (rq->origusername)
931 free(rq->origusername);
937 radmsg_free(rq->msg);
941 void freerqoutdata(struct rqout *rqout) {
945 if (rqout->rq->buf) {
946 free(rqout->rq->buf);
947 rqout->rq->buf = NULL;
953 memset(&rqout->expiry, 0, sizeof(struct timeval));
956 void sendrq(struct request *rq) {
960 removeclientrqs_sendrq_freeserver_lock(1);
965 start = to->conf->statusserver ? 1 : 0;
966 pthread_mutex_lock(&to->newrq_mutex);
967 if (start && rq->msg->code == RAD_Status_Server) {
968 pthread_mutex_lock(to->requests[0].lock);
969 if (to->requests[0].rq) {
970 pthread_mutex_unlock(to->requests[0].lock);
971 debug(DBG_WARN, "sendrq: status server already in queue, dropping request");
978 /* might simplify if only try nextid, might be ok */
979 for (i = to->nextid; i < MAX_REQUESTS; i++) {
980 if (!to->requests[i].rq) {
981 pthread_mutex_lock(to->requests[i].lock);
982 if (!to->requests[i].rq)
984 pthread_mutex_unlock(to->requests[i].lock);
987 if (i == MAX_REQUESTS) {
988 for (i = start; i < to->nextid; i++) {
989 if (!to->requests[i].rq) {
990 pthread_mutex_lock(to->requests[i].lock);
991 if (!to->requests[i].rq)
993 pthread_mutex_unlock(to->requests[i].lock);
996 if (i == to->nextid) {
997 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
1002 rq->newid = (uint8_t)i;
1003 rq->msg->id = (uint8_t)i;
1004 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
1006 pthread_mutex_unlock(to->requests[i].lock);
1007 debug(DBG_ERR, "sendrq: radmsg2buf failed");
1011 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1012 to->requests[i].rq = rq;
1013 pthread_mutex_unlock(to->requests[i].lock);
1014 if (i >= start) /* i is not reserved for statusserver */
1019 debug(DBG_DBG, "sendrq: signalling client writer");
1020 pthread_cond_signal(&to->newrq_cond);
1023 pthread_mutex_unlock(&to->newrq_mutex);
1024 removeclientrqs_sendrq_freeserver_lock(0);
1029 rmclientrq(rq, rq->msg->id);
1031 pthread_mutex_unlock(&to->newrq_mutex);
1032 removeclientrqs_sendrq_freeserver_lock(0);
1035 void sendreply(struct request *rq) {
1037 struct client *to = rq->from;
1040 rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
1041 radmsg_free(rq->msg);
1043 if (!rq->replybuf) {
1045 debug(DBG_ERR, "sendreply: radmsg2buf failed");
1049 pthread_mutex_lock(&to->replyq->mutex);
1050 first = list_first(to->replyq->entries) == NULL;
1052 if (!list_push(to->replyq->entries, rq)) {
1053 pthread_mutex_unlock(&to->replyq->mutex);
1055 debug(DBG_ERR, "sendreply: malloc failed");
1060 debug(DBG_DBG, "signalling server writer");
1061 pthread_cond_signal(&to->replyq->cond);
1063 pthread_mutex_unlock(&to->replyq->mutex);
1066 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1067 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1068 static unsigned char first = 1;
1069 static EVP_MD_CTX mdctx;
1070 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1071 unsigned int md_len;
1072 uint8_t i, offset = 0, out[128];
1074 pthread_mutex_lock(&lock);
1076 EVP_MD_CTX_init(&mdctx);
1082 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1083 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1084 !EVP_DigestUpdate(&mdctx, input, 16) ||
1085 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1087 pthread_mutex_unlock(&lock);
1090 for (i = 0; i < 16; i++)
1091 out[offset + i] = hash[i] ^ in[offset + i];
1092 input = out + offset - 16;
1097 memcpy(in, out, len);
1098 pthread_mutex_unlock(&lock);
1102 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1103 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1104 static unsigned char first = 1;
1105 static EVP_MD_CTX mdctx;
1106 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1107 unsigned int md_len;
1108 uint8_t i, offset = 0, out[128];
1110 pthread_mutex_lock(&lock);
1112 EVP_MD_CTX_init(&mdctx);
1118 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1119 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1120 !EVP_DigestUpdate(&mdctx, input, 16) ||
1121 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1123 pthread_mutex_unlock(&lock);
1126 for (i = 0; i < 16; i++)
1127 out[offset + i] = hash[i] ^ in[offset + i];
1128 input = in + offset;
1133 memcpy(in, out, len);
1134 pthread_mutex_unlock(&lock);
1138 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1139 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1140 static unsigned char first = 1;
1141 static EVP_MD_CTX mdctx;
1142 unsigned char hash[EVP_MAX_MD_SIZE];
1143 unsigned int md_len;
1146 pthread_mutex_lock(&lock);
1148 EVP_MD_CTX_init(&mdctx);
1153 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1154 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1155 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1158 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1159 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1160 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1161 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1162 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1163 pthread_mutex_unlock(&lock);
1168 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1171 for (i = 0; i < 16; i++)
1174 for (offset = 16; offset < len; offset += 16) {
1176 printf("text + offset - 16 c(%d): ", offset / 16);
1177 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1179 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1180 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1181 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1182 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1184 pthread_mutex_unlock(&lock);
1188 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1191 for (i = 0; i < 16; i++)
1192 text[offset + i] ^= hash[i];
1196 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1199 pthread_mutex_unlock(&lock);
1203 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1204 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1205 static unsigned char first = 1;
1206 static EVP_MD_CTX mdctx;
1207 unsigned char hash[EVP_MAX_MD_SIZE];
1208 unsigned int md_len;
1212 pthread_mutex_lock(&lock);
1214 EVP_MD_CTX_init(&mdctx);
1219 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1220 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1221 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1224 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1225 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1226 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1227 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1228 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1229 pthread_mutex_unlock(&lock);
1234 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1237 for (i = 0; i < 16; i++)
1238 plain[i] = text[i] ^ hash[i];
1240 for (offset = 16; offset < len; offset += 16) {
1242 printf("text + offset - 16 c(%d): ", offset / 16);
1243 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1245 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1246 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1247 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1248 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1250 pthread_mutex_unlock(&lock);
1254 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1257 for (i = 0; i < 16; i++)
1258 plain[offset + i] = text[offset + i] ^ hash[i];
1261 memcpy(text, plain, len);
1263 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1266 pthread_mutex_unlock(&lock);
1270 struct realm *newrealmref(struct realm *r) {
1276 /* returns with lock on realm */
1277 struct realm *id2realm(struct list *realmlist, char *id) {
1278 struct list_node *entry;
1279 struct realm *realm, *subrealm;
1281 /* need to do locking for subrealms and check subrealm timers */
1282 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1283 realm = (struct realm *)entry->data;
1284 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1285 pthread_mutex_lock(&realm->mutex);
1286 if (realm->subrealms) {
1287 subrealm = id2realm(realm->subrealms, id);
1289 pthread_mutex_unlock(&realm->mutex);
1293 return newrealmref(realm);
1299 /* helper function, only used by removeserversubrealms() */
1300 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1301 struct list_node *entry, *entry2;
1302 struct realm *realm;
1304 for (entry = list_first(realmlist); entry;) {
1305 realm = newrealmref((struct realm *)entry->data);
1306 pthread_mutex_lock(&realm->mutex);
1307 entry = list_next(entry);
1309 if (realm->srvconfs) {
1310 for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
1311 if (entry2->data == srv)
1313 list_removedata(realm->srvconfs, srv);
1314 if (!list_first(realm->srvconfs)) {
1315 list_destroy(realm->srvconfs);
1316 realm->srvconfs = NULL;
1319 if (realm->accsrvconfs) {
1320 for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
1321 if (entry2->data == srv)
1323 list_removedata(realm->accsrvconfs, srv);
1324 if (!list_first(realm->accsrvconfs)) {
1325 list_destroy(realm->accsrvconfs);
1326 realm->accsrvconfs = NULL;
1330 /* remove subrealm if no servers */
1331 if (!realm->srvconfs && !realm->accsrvconfs)
1332 list_removedata(realmlist, realm);
1334 pthread_mutex_unlock(&realm->mutex);
1339 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1340 struct list_node *entry;
1341 struct realm *realm;
1343 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1344 realm = (struct realm *)entry->data;
1345 pthread_mutex_lock(&realm->mutex);
1346 if (realm->subrealms) {
1347 _internal_removeserversubrealms(realm->subrealms, srv);
1348 if (!list_first(realm->subrealms)) {
1349 list_destroy(realm->subrealms);
1350 realm->subrealms = NULL;
1353 pthread_mutex_unlock(&realm->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, uint8_t *oldauth, uint8_t *newauth) {
1398 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1399 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1402 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), 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->rqauth))
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 /* returns 1 if entire element is to be removed, else 0 */
1432 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
1433 uint8_t alen, sublen;
1437 if (!removevendorattrs)
1440 memcpy(&vendor, attr->v, 4);
1441 vendor = ntohl(vendor);
1442 while (*removevendorattrs && *removevendorattrs != vendor)
1443 removevendorattrs += 2;
1444 if (!*removevendorattrs)
1447 if (findvendorsubattr(removevendorattrs, vendor, -1))
1448 return 1; /* remove entire vendor attribute */
1450 sublen = attr->l - 4;
1451 subattrs = attr->v + 4;
1453 if (!attrvalidate(subattrs, sublen)) {
1454 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1458 while (sublen > 1) {
1459 alen = ATTRLEN(subattrs);
1461 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1462 memmove(subattrs, subattrs + alen, sublen);
1470 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
1471 struct list_node *n, *p;
1475 n = list_first(msg->attrs);
1477 attr = (struct tlv *)n->data;
1478 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
1479 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
1480 list_removedata(msg->attrs, attr);
1482 n = p ? list_next(p) : list_first(msg->attrs);
1489 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
1490 struct list_node *n;
1493 for (n = list_first(addattrs); n; n = list_next(n)) {
1494 a = copytlv((struct tlv *)n->data);
1497 if (!radmsg_add(msg, a)) {
1505 int resizeattr(struct tlv *attr, uint8_t newlen) {
1508 if (newlen != attr->l) {
1509 newv = realloc(attr->v, newlen);
1518 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1519 size_t nmatch = 10, reslen = 0, start = 0;
1520 regmatch_t pmatch[10], *pfield;
1524 in = stringcopy((char *)attr->v, attr->l);
1528 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1533 out = modattr->replacement;
1535 for (i = start; out[i]; i++) {
1536 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1537 pfield = &pmatch[out[i + 1] - '0'];
1538 if (pfield->rm_so >= 0) {
1539 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1545 reslen += i - start;
1547 debug(DBG_WARN, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1552 if (!resizeattr(attr, reslen)) {
1559 for (i = start; out[i]; i++) {
1560 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1561 pfield = &pmatch[out[i + 1] - '0'];
1562 if (pfield->rm_so >= 0) {
1563 memcpy(attr->v + reslen, out + start, i - start);
1564 reslen += i - start;
1565 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1566 reslen += pfield->rm_eo - pfield->rm_so;
1573 memcpy(attr->v + reslen, out + start, i - start);
1577 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1578 struct list_node *n, *m;
1580 for (n = list_first(msg->attrs); n; n = list_next(n))
1581 for (m = list_first(modattrs); m; m = list_next(m))
1582 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1583 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1588 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1591 if (rewrite->removeattrs || rewrite->removevendorattrs)
1592 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1593 if (rewrite->addattrs && !dorewriteadd(msg, rewrite->addattrs))
1595 if (rewrite->modattrs && !dorewritemod(msg, rewrite->modattrs))
1600 int rewriteusername(struct request *rq, struct tlv *attr) {
1601 char *orig = (char *)tlv2str(attr);
1602 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1606 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1607 rq->origusername = (char *)orig;
1613 int addvendorattr(struct radmsg *msg, uint32_t vendor, struct tlv *attr) {
1620 vendor = htonl(vendor);
1621 memcpy(v, &vendor, 4);
1622 tlv2buf(v + 4, attr);
1624 vattr = maketlv(RAD_Attr_Vendor_Specific, l, v);
1625 if (vattr && radmsg_add(msg, vattr))
1632 void addttlattr(struct radmsg *msg, uint32_t *attrtype, uint8_t addttl) {
1639 if (attrtype[1] == -1) { /* not vendor */
1640 attr = maketlv(attrtype[0], 4, ttl);
1641 if (attr && !radmsg_add(msg, attr))
1644 attr = maketlv(attrtype[1], 4, ttl);
1646 addvendorattr(msg, attrtype[0], attr);
1652 int decttl(uint8_t l, uint8_t *v) {
1659 while (i >= 0 && !v[i])
1663 for (i--; i >= 0 && !v[i]; i--);
1672 /* returns -1 if no ttl, 0 if exceeded, 1 if ok */
1673 int checkttl(struct radmsg *msg, uint32_t *attrtype) {
1674 uint8_t alen, *subattrs;
1676 struct list_node *node;
1680 if (attrtype[1] == -1) { /* not vendor */
1681 attr = radmsg_gettype(msg, attrtype[0]);
1683 return decttl(attr->l, attr->v);
1685 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1686 attr = (struct tlv *)node->data;
1687 if (attr->t != RAD_Attr_Vendor_Specific || attr->l <= 4)
1689 memcpy(&vendor, attr->v, 4);
1690 if (ntohl(vendor) != attrtype[0])
1692 sublen = attr->l - 4;
1693 subattrs = attr->v + 4;
1694 if (!attrvalidate(subattrs, sublen))
1696 while (sublen > 1) {
1697 if (ATTRTYPE(subattrs) == attrtype[1])
1698 return decttl(ATTRVALLEN(subattrs), ATTRVAL(subattrs));
1699 alen = ATTRLEN(subattrs);
1707 const char *radmsgtype2string(uint8_t code) {
1708 static const char *rad_msg_names[] = {
1709 "", "Access-Request", "Access-Accept", "Access-Reject",
1710 "Accounting-Request", "Accounting-Response", "", "",
1711 "", "", "", "Access-Challenge",
1712 "Status-Server", "Status-Client"
1714 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1717 void char2hex(char *h, unsigned char c) {
1718 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1719 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1720 h[0] = hexdigits[c / 16];
1721 h[1] = hexdigits[c % 16];
1725 uint8_t *radattr2ascii(struct tlv *attr) {
1733 for (i = 0; i < attr->l; i++)
1734 if (attr->v[i] < 32 || attr->v[i] > 126)
1737 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1744 for (i = 0; i < attr->l; i++)
1745 if (attr->v[i] < 32 || attr->v[i] > 126) {
1747 char2hex((char *)d, attr->v[i]);
1755 void acclog(struct radmsg *msg, char *host) {
1759 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1761 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1764 username = radattr2ascii(attr);
1766 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1771 void respond(struct request *rq, uint8_t code, char *message) {
1775 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1777 debug(DBG_ERR, "respond: malloc failed");
1780 if (message && *message) {
1781 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1782 if (!attr || !radmsg_add(msg, attr)) {
1785 debug(DBG_ERR, "respond: malloc failed");
1790 radmsg_free(rq->msg);
1792 debug(DBG_DBG, "respond: sending %s to %s", radmsgtype2string(msg->code), rq->from->conf->host);
1793 sendreply(newrqref(rq));
1796 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1797 struct list_node *entry;
1798 struct clsrvconf *server, *best = NULL, *first = NULL;
1800 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1801 server = (struct clsrvconf *)entry->data;
1802 if (!server->servers)
1806 if (!server->servers->connectionok)
1808 if (!server->servers->lostrqs)
1814 if (server->servers->lostrqs < best->servers->lostrqs)
1817 return best ? best : first;
1820 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1821 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1822 struct clsrvconf *srvconf;
1823 struct realm *subrealm;
1824 struct server *server = NULL;
1825 char *id = (char *)tlv2str(username);
1829 /* returns with lock on realm */
1830 *realm = id2realm(realms, id);
1833 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1834 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1837 server = srvconf->servers;
1838 if (!acc && !(*realm)->parent && !srvconf->servers) {
1839 subrealm = adddynamicrealmserver(*realm, srvconf, id);
1841 pthread_mutex_lock(&subrealm->mutex);
1842 pthread_mutex_unlock(&(*realm)->mutex);
1845 server = ((struct clsrvconf *)subrealm->srvconfs->first->data)->servers;
1854 struct request *newrequest() {
1857 rq = malloc(sizeof(struct request));
1859 debug(DBG_ERR, "newrequest: malloc failed");
1862 memset(rq, 0, sizeof(struct request));
1864 gettimeofday(&rq->created, NULL);
1868 int addclientrq(struct request *rq) {
1872 r = rq->from->rqs[rq->rqid];
1874 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1875 gettimeofday(&now, NULL);
1876 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1878 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1879 sendreply(newrqref(r));
1881 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1887 rq->from->rqs[rq->rqid] = newrqref(rq);
1891 void rmclientrq(struct request *rq, uint8_t id) {
1894 r = rq->from->rqs[id];
1897 rq->from->rqs[id] = NULL;
1901 /* returns 0 if validation/authentication fails, else 1 */
1902 int radsrv(struct request *rq) {
1903 struct radmsg *msg = NULL;
1905 uint8_t *userascii = NULL;
1906 struct realm *realm = NULL;
1907 struct server *to = NULL;
1908 struct client *from = rq->from;
1911 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1916 debug(DBG_WARN, "radsrv: message validation failed, ignoring packet");
1923 memcpy(rq->rqauth, msg->auth, 16);
1925 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1926 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1927 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1931 if (!addclientrq(rq))
1934 if (msg->code == RAD_Status_Server) {
1935 respond(rq, RAD_Access_Accept, NULL);
1939 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1941 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1944 ttlres = checkttl(msg, options.ttlattrtype);
1946 debug(DBG_WARN, "radsrv: ignoring request from client %s (%s), ttl exceeded", from->conf->name, addr2string(from->addr));
1950 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1952 if (msg->code == RAD_Accounting_Request) {
1953 acclog(msg, from->conf->host);
1954 respond(rq, RAD_Accounting_Response, NULL);
1956 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1960 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1961 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1965 userascii = radattr2ascii(attr);
1968 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1970 /* will return with lock on the realm */
1971 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1973 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1978 if (realm->message && msg->code == RAD_Access_Request) {
1979 debug(DBG_INFO, "radsrv: sending reject to %s for %s", from->conf->host, userascii);
1980 respond(rq, RAD_Access_Reject, realm->message);
1981 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1982 acclog(msg, from->conf->host);
1983 respond(rq, RAD_Accounting_Response, NULL);
1988 if (options.loopprevention && !strcmp(from->conf->name, to->conf->name)) {
1989 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s (%s) to server %s, discarding",
1990 from->conf->name, addr2string(from->addr), to->conf->name);
1994 if (msg->code == RAD_Accounting_Request)
1995 memset(msg->auth, 0, 16);
1996 else if (!RAND_bytes(msg->auth, 16)) {
1997 debug(DBG_WARN, "radsrv: failed to generate random auth");
2002 printfchars(NULL, "auth", "%02x ", auth, 16);
2005 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
2007 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
2008 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
2012 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
2014 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
2015 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
2019 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
2022 if (ttlres == -1 && (options.addttl || to->conf->addttl))
2023 addttlattr(msg, options.ttlattrtype, to->conf->addttl ? to->conf->addttl : options.addttl);
2028 pthread_mutex_unlock(&realm->mutex);
2033 rmclientrq(rq, msg->id);
2038 pthread_mutex_unlock(&realm->mutex);
2044 void replyh(struct server *server, unsigned char *buf) {
2045 struct client *from;
2046 struct rqout *rqout;
2048 unsigned char *subattrs;
2049 uint8_t *username, *stationid, *replymsg;
2050 struct radmsg *msg = NULL;
2052 struct list_node *node;
2054 server->connectionok = 1;
2055 server->lostrqs = 0;
2057 rqout = server->requests + buf[1];
2058 pthread_mutex_lock(rqout->lock);
2059 if (!rqout->tries) {
2062 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
2066 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
2070 debug(DBG_WARN, "replyh: message validation failed, ignoring packet");
2073 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
2074 && msg->code != RAD_Accounting_Response) {
2075 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
2078 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
2080 gettimeofday(&server->lastrcv, NULL);
2082 if (rqout->rq->msg->code == RAD_Status_Server) {
2083 freerqoutdata(rqout);
2084 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2088 gettimeofday(&server->lastreply, NULL);
2089 from = rqout->rq->from;
2091 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
2092 debug(DBG_WARN, "replyh: rewritein failed");
2096 ttlres = checkttl(msg, options.ttlattrtype);
2098 debug(DBG_WARN, "replyh: ignoring reply from server %s, ttl exceeded", server->conf->host);
2103 for (node = list_first(msg->attrs); node; node = list_next(node)) {
2104 attr = (struct tlv *)node->data;
2105 if (attr->t != RAD_Attr_Vendor_Specific)
2109 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
2112 sublen = attr->l - 4;
2113 subattrs = attr->v + 4;
2114 if (!attrvalidate(subattrs, sublen) ||
2115 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2116 rqout->rq, server->conf->secret, from->conf->secret) ||
2117 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2118 rqout->rq, server->conf->secret, from->conf->secret))
2122 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2126 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
2127 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
2129 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
2130 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
2133 debug(DBG_INFO, "%s for user %s stationid %s from %s (%s)",
2134 radmsgtype2string(msg->code), username, stationid, server->conf->host, replymsg);
2137 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2138 radmsgtype2string(msg->code), username, stationid, server->conf->host);
2142 debug(DBG_INFO, "%s for user %s from %s (%s)",
2143 radmsgtype2string(msg->code), username, server->conf->host, replymsg);
2146 debug(DBG_INFO, "%s for user %s from %s",
2147 radmsgtype2string(msg->code), username, server->conf->host);
2153 msg->id = (char)rqout->rq->rqid;
2154 memcpy(msg->auth, rqout->rq->rqauth, 16);
2157 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2160 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
2161 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
2162 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2165 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
2168 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
2169 debug(DBG_WARN, "replyh: rewriteout failed");
2173 if (ttlres == -1 && (options.addttl || from->conf->addttl))
2174 addttlattr(msg, options.ttlattrtype, from->conf->addttl ? from->conf->addttl : options.addttl);
2176 debug(DBG_INFO, "replyh: passing reply to client %s (%s)", from->conf->name, addr2string(from->addr));
2177 radmsg_free(rqout->rq->msg);
2178 rqout->rq->msg = msg;
2179 sendreply(newrqref(rqout->rq));
2180 freerqoutdata(rqout);
2181 pthread_mutex_unlock(rqout->lock);
2186 pthread_mutex_unlock(rqout->lock);
2190 struct request *createstatsrvrq() {
2197 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
2200 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
2203 if (!radmsg_add(rq->msg, attr)) {
2214 /* code for removing state not finished */
2215 void *clientwr(void *arg) {
2216 struct server *server = (struct server *)arg;
2217 struct rqout *rqout = NULL;
2218 pthread_t clientrdth;
2219 int i, dynconffail = 0;
2222 struct timeval now, laststatsrv;
2223 struct timespec timeout;
2224 struct request *statsrvrq;
2225 struct clsrvconf *conf;
2227 conf = server->conf;
2229 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2234 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2235 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2239 memset(&timeout, 0, sizeof(struct timespec));
2241 if (conf->statusserver) {
2242 gettimeofday(&server->lastrcv, NULL);
2243 gettimeofday(&laststatsrv, NULL);
2246 if (conf->pdef->connecter) {
2247 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2249 server->connectionok = 1;
2250 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
2251 debug(DBG_ERR, "clientwr: pthread_create failed");
2255 server->connectionok = 1;
2258 pthread_mutex_lock(&server->newrq_mutex);
2259 if (!server->newrq) {
2260 gettimeofday(&now, NULL);
2261 /* random 0-7 seconds */
2262 RAND_bytes(&rnd, 1);
2264 if (conf->statusserver) {
2265 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2266 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
2268 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
2269 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
2271 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2272 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2275 if (timeout.tv_sec > now.tv_sec)
2276 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2278 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2281 if (server->newrq) {
2282 debug(DBG_DBG, "clientwr: got new request");
2287 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2289 pthread_mutex_unlock(&server->newrq_mutex);
2291 for (i = 0; i < MAX_REQUESTS; i++) {
2292 if (server->clientrdgone) {
2293 pthread_join(clientrdth, NULL);
2297 for (; i < MAX_REQUESTS; i++) {
2298 rqout = server->requests + i;
2300 pthread_mutex_lock(rqout->lock);
2303 pthread_mutex_unlock(rqout->lock);
2307 if (i == MAX_REQUESTS)
2310 gettimeofday(&now, NULL);
2311 if (now.tv_sec < rqout->expiry.tv_sec) {
2312 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2313 timeout.tv_sec = rqout->expiry.tv_sec;
2314 pthread_mutex_unlock(rqout->lock);
2318 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2319 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2320 if (conf->statusserver) {
2321 if (*rqout->rq->buf == RAD_Status_Server) {
2322 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2323 if (server->lostrqs < 255)
2327 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2328 if (server->lostrqs < 255)
2331 freerqoutdata(rqout);
2332 pthread_mutex_unlock(rqout->lock);
2336 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2337 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2338 timeout.tv_sec = rqout->expiry.tv_sec;
2340 conf->pdef->clientradput(server, rqout->rq->buf);
2341 pthread_mutex_unlock(rqout->lock);
2343 if (conf->statusserver && server->connectionok) {
2344 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2345 gettimeofday(&now, NULL);
2346 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
2348 statsrvrq = createstatsrvrq();
2350 statsrvrq->to = server;
2351 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2358 conf->servers = NULL;
2359 if (server->dynamiclookuparg) {
2360 removeserversubrealms(realms, conf);
2364 freeclsrvconf(conf);
2366 freeserver(server, 1);
2367 ERR_remove_state(0);
2371 void createlistener(uint8_t type, char *arg) {
2373 struct clsrvconf *listenres;
2374 struct addrinfo *res;
2375 int s = -1, on = 1, *sp = NULL;
2377 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2379 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2381 for (res = listenres->addrinfo; res; res = res->ai_next) {
2382 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2384 debug(DBG_WARN, "createlistener: socket failed");
2387 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2389 if (res->ai_family == AF_INET6)
2390 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2392 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2393 debug(DBG_WARN, "createlistener: bind failed");
2399 sp = malloc(sizeof(int));
2401 debugx(1, DBG_ERR, "malloc failed");
2403 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
2404 debugx(1, DBG_ERR, "pthread_create failed");
2408 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2410 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
2411 listenres->host ? listenres->host : "*", listenres->port);
2412 freeclsrvres(listenres);
2415 void createlisteners(uint8_t type, char **args) {
2419 for (i = 0; args[i]; i++)
2420 createlistener(type, args[i]);
2422 createlistener(type, NULL);
2426 void ssl_info_callback(const SSL *ssl, int where, int ret) {
2430 w = where & ~SSL_ST_MASK;
2432 if (w & SSL_ST_CONNECT)
2434 else if (w & SSL_ST_ACCEPT)
2439 if (where & SSL_CB_LOOP)
2440 debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
2441 else if (where & SSL_CB_ALERT) {
2442 s = (where & SSL_CB_READ) ? "read" : "write";
2443 debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
2445 else if (where & SSL_CB_EXIT) {
2447 debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
2449 debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
2459 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2460 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2461 for (i = 0; i < CRYPTO_num_locks(); i++) {
2462 ssl_lock_count[i] = 0;
2463 pthread_mutex_init(&ssl_locks[i], NULL);
2465 CRYPTO_set_id_callback(ssl_thread_id);
2466 CRYPTO_set_locking_callback(ssl_locking_callback);
2468 SSL_load_error_strings();
2471 while (!RAND_status()) {
2474 RAND_seed((unsigned char *)&t, sizeof(time_t));
2475 RAND_seed((unsigned char *)&pid, sizeof(pid));
2479 X509_VERIFY_PARAM *createverifyparams(char **poids) {
2480 X509_VERIFY_PARAM *pm;
2481 ASN1_OBJECT *pobject;
2484 pm = X509_VERIFY_PARAM_new();
2488 for (i = 0; poids[i]; i++) {
2489 pobject = OBJ_txt2obj(poids[i], 0);
2491 X509_VERIFY_PARAM_free(pm);
2494 X509_VERIFY_PARAM_add0_policy(pm, pobject);
2497 X509_VERIFY_PARAM_set_flags(pm, X509_V_FLAG_POLICY_CHECK | X509_V_FLAG_EXPLICIT_POLICY);
2501 int tlsaddcacrl(SSL_CTX *ctx, struct tls *conf) {
2502 STACK_OF(X509_NAME) *calist;
2504 unsigned long error;
2506 if (!SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2507 while ((error = ERR_get_error()))
2508 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2509 debug(DBG_ERR, "tlsaddcacrl: Error updating TLS context %s", conf->name);
2513 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2514 if (!conf->cacertfile || calist) {
2515 if (conf->cacertpath) {
2517 calist = sk_X509_NAME_new_null();
2518 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2519 sk_X509_NAME_free(calist);
2525 while ((error = ERR_get_error()))
2526 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2527 debug(DBG_ERR, "tlsaddcacrl: Error adding CA subjects in TLS context %s", conf->name);
2530 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2531 SSL_CTX_set_client_CA_list(ctx, calist);
2533 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2534 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2536 if (conf->crlcheck || conf->vpm) {
2537 x509_s = SSL_CTX_get_cert_store(ctx);
2539 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2541 X509_STORE_set1_param(x509_s, conf->vpm);
2544 debug(DBG_DBG, "tlsaddcacrl: updated TLS context %s", conf->name);
2548 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2549 SSL_CTX *ctx = NULL;
2550 unsigned long error;
2557 ctx = SSL_CTX_new(TLSv1_method());
2559 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2563 ctx = SSL_CTX_new(DTLSv1_method());
2565 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2567 SSL_CTX_set_read_ahead(ctx, 1);
2571 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2575 if (conf->certkeypwd) {
2576 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2577 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2579 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2580 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2581 !SSL_CTX_check_private_key(ctx)) {
2582 while ((error = ERR_get_error()))
2583 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2584 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2589 if (conf->policyoids) {
2591 conf->vpm = createverifyparams(conf->policyoids);
2593 debug(DBG_ERR, "tlsaddcacrl: Failed to add policyOIDs in TLS context %s", conf->name);
2600 if (!tlsaddcacrl(ctx, conf)) {
2602 X509_VERIFY_PARAM_free(conf->vpm);
2609 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
2613 struct tls *tlsgettls(char *alt1, char *alt2) {
2616 t = hash_read(tlsconfs, alt1, strlen(alt1));
2618 t = hash_read(tlsconfs, alt2, strlen(alt2));
2622 SSL_CTX *tlsgetctx(uint8_t type, struct tls *t) {
2627 gettimeofday(&now, NULL);
2631 if (t->tlsexpiry && t->tlsctx) {
2632 if (t->tlsexpiry < now.tv_sec) {
2633 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
2634 tlsaddcacrl(t->tlsctx, t);
2638 t->tlsctx = tlscreatectx(RAD_TLS, t);
2640 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
2644 if (t->dtlsexpiry && t->dtlsctx) {
2645 if (t->dtlsexpiry < now.tv_sec) {
2646 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
2647 tlsaddcacrl(t->dtlsctx, t);
2651 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2653 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
2660 struct list *addsrvconfs(char *value, char **names) {
2661 struct list *conflist;
2663 struct list_node *entry;
2664 struct clsrvconf *conf = NULL;
2666 if (!names || !*names)
2669 conflist = list_create();
2671 debug(DBG_ERR, "malloc failed");
2675 for (n = 0; names[n]; n++) {
2676 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2677 conf = (struct clsrvconf *)entry->data;
2678 if (!strcasecmp(names[n], conf->name))
2682 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2683 list_destroy(conflist);
2686 if (!list_push(conflist, conf)) {
2687 debug(DBG_ERR, "malloc failed");
2688 list_destroy(conflist);
2691 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2696 void freerealm(struct realm *realm) {
2699 debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2700 if (--realm->refcount)
2704 free(realm->message);
2705 regfree(&realm->regex);
2706 pthread_mutex_destroy(&realm->mutex);
2707 /* if refcount == 0, all subrealms gone */
2708 list_destroy(realm->subrealms);
2709 /* if refcount == 0, all srvconfs gone */
2710 list_destroy(realm->srvconfs);
2711 /* if refcount == 0, all accsrvconfs gone */
2712 list_destroy(realm->accsrvconfs);
2713 freerealm(realm->parent);
2717 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2719 struct realm *realm;
2720 char *s, *regex = NULL;
2722 if (*value == '/') {
2723 /* regexp, remove optional trailing / if present */
2724 if (value[strlen(value) - 1] == '/')
2725 value[strlen(value) - 1] = '\0';
2727 /* not a regexp, let us make it one */
2728 if (*value == '*' && !value[1])
2729 regex = stringcopy(".*", 0);
2731 for (n = 0, s = value; *s;)
2734 regex = malloc(strlen(value) + n + 3);
2737 for (n = 1, s = value; *s; s++) {
2747 debug(DBG_ERR, "malloc failed");
2751 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2754 realm = malloc(sizeof(struct realm));
2756 debug(DBG_ERR, "malloc failed");
2759 memset(realm, 0, sizeof(struct realm));
2761 if (pthread_mutex_init(&realm->mutex, NULL)) {
2762 debug(DBG_ERR, "mutex init failed");
2768 realm->name = stringcopy(value, 0);
2770 debug(DBG_ERR, "malloc failed");
2773 if (message && strlen(message) > 253) {
2774 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2777 realm->message = message;
2778 realm->accresp = accresp;
2780 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2781 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2785 if (servers && *servers) {
2786 realm->srvconfs = addsrvconfs(value, servers);
2787 if (!realm->srvconfs)
2791 if (accservers && *accservers) {
2792 realm->accsrvconfs = addsrvconfs(value, accservers);
2793 if (!realm->accsrvconfs)
2797 if (!list_push(realmlist, realm)) {
2798 debug(DBG_ERR, "malloc failed");
2799 pthread_mutex_destroy(&realm->mutex);
2803 debug(DBG_DBG, "addrealm: added realm %s", value);
2807 while (list_shift(realm->srvconfs));
2808 while (list_shift(realm->accsrvconfs));
2815 for (n = 0; servers[n]; n++)
2817 freegconfmstr(servers);
2821 for (n = 0; accservers[n]; n++)
2823 freegconfmstr(accservers);
2825 return newrealmref(realm);
2828 struct realm *adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2829 struct clsrvconf *srvconf;
2830 struct realm *newrealm = NULL;
2831 char *realmname, *s;
2834 if (!conf->dynamiclookupcommand)
2837 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2838 realmname = strrchr(id, '@');
2844 for (s = realmname; *s; s++)
2845 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2848 srvconf = malloc(sizeof(struct clsrvconf));
2850 debug(DBG_ERR, "malloc failed");
2854 if (!addserver(srvconf))
2857 if (!realm->subrealms)
2858 realm->subrealms = list_create();
2859 if (!realm->subrealms)
2861 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2864 newrealm->parent = newrealmref(realm);
2866 /* add server and accserver to newrealm */
2867 newrealm->srvconfs = list_create();
2868 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2869 debug(DBG_ERR, "malloc failed");
2872 newrealmref(newrealm);
2873 newrealm->accsrvconfs = list_create();
2874 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2875 debug(DBG_ERR, "malloc failed");
2876 list_shift(realm->srvconfs);
2877 freerealm(newrealm);
2880 newrealmref(newrealm);
2882 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2883 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2884 debug(DBG_ERR, "pthread_create failed");
2885 list_shift(realm->srvconfs);
2886 freerealm(newrealm);
2887 list_shift(realm->accsrvconfs);
2888 freerealm(newrealm);
2891 pthread_detach(clientth);
2896 list_removedata(realm->subrealms, newrealm);
2897 freerealm(newrealm);
2898 if (!list_first(realm->subrealms)) {
2899 list_destroy(realm->subrealms);
2900 realm->subrealms = NULL;
2903 freeserver(srvconf->servers, 1);
2905 debug(DBG_ERR, "failed to create dynamic server");
2909 int dynamicconfig(struct server *server) {
2910 int ok, fd[2], status;
2912 struct clsrvconf *conf = server->conf;
2913 struct gconffile *cf = NULL;
2915 /* for now we only learn hostname/address */
2916 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2919 debug(DBG_ERR, "dynamicconfig: pipe error");
2924 debug(DBG_ERR, "dynamicconfig: fork error");
2928 } else if (pid == 0) {
2931 if (fd[1] != STDOUT_FILENO) {
2932 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2933 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2936 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2937 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2941 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2942 ok = getgenericconfig(&cf, NULL,
2943 "Server", CONF_CBK, confserver_cb, (void *)conf,
2948 if (waitpid(pid, &status, 0) < 0) {
2949 debug(DBG_ERR, "dynamicconfig: wait error");
2954 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2962 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2966 int addmatchcertattr(struct clsrvconf *conf) {
2970 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2971 r = &conf->certcnregex;
2972 v = conf->matchcertattr + 4;
2973 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2974 r = &conf->certuriregex;
2975 v = conf->matchcertattr + 20;
2980 /* regexp, remove optional trailing / if present */
2981 if (v[strlen(v) - 1] == '/')
2982 v[strlen(v) - 1] = '\0';
2986 *r = malloc(sizeof(regex_t));
2988 debug(DBG_ERR, "malloc failed");
2991 if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2994 debug(DBG_ERR, "failed to compile regular expression %s", v);
3000 /* should accept both names and numeric values, only numeric right now */
3001 uint8_t attrname2val(char *attrname) {
3004 val = atoi(attrname);
3005 return val > 0 && val < 256 ? val : 0;
3008 /* should accept both names and numeric values, only numeric right now */
3009 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
3012 *vendor = atoi(attrname);
3013 s = strchr(attrname, ':');
3018 *type = atoi(s + 1);
3019 return *type >= 0 && *type < 256;
3022 /* should accept both names and numeric values, only numeric right now */
3023 struct tlv *extractattr(char *nameval) {
3028 s = strchr(nameval, ':');
3029 name = atoi(nameval);
3030 if (!s || name < 1 || name > 255)
3032 len = strlen(s + 1);
3035 a = malloc(sizeof(struct tlv));
3038 a->v = (uint8_t *)stringcopy(s + 1, 0);
3048 /* should accept both names and numeric values, only numeric right now */
3049 struct modattr *extractmodattr(char *nameval) {
3054 if (!strncasecmp(nameval, "User-Name:/", 11)) {
3058 s = strchr(nameval, ':');
3059 name = atoi(nameval);
3060 if (!s || name < 1 || name > 255 || s[1] != '/')
3064 /* regexp, remove optional trailing / if present */
3065 if (s[strlen(s) - 1] == '/')
3066 s[strlen(s) - 1] = '\0';
3074 m = malloc(sizeof(struct modattr));
3076 debug(DBG_ERR, "malloc failed");
3081 m->replacement = stringcopy(t, 0);
3082 if (!m->replacement) {
3084 debug(DBG_ERR, "malloc failed");
3088 m->regex = malloc(sizeof(regex_t));
3090 free(m->replacement);
3092 debug(DBG_ERR, "malloc failed");
3096 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
3098 free(m->replacement);
3100 debug(DBG_ERR, "failed to compile regular expression %s", s);
3107 struct rewrite *getrewrite(char *alt1, char *alt2) {
3110 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
3112 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
3117 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
3118 struct rewrite *rewrite = NULL;
3120 uint8_t *rma = NULL;
3121 uint32_t *p, *rmva = NULL;
3122 struct list *adda = NULL, *moda = NULL;
3127 for (n = 0; rmattrs[n]; n++);
3128 rma = calloc(n + 1, sizeof(uint8_t));
3130 debugx(1, DBG_ERR, "malloc failed");
3132 for (i = 0; i < n; i++)
3133 if (!(rma[i] = attrname2val(rmattrs[i])))
3134 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
3135 freegconfmstr(rmattrs);
3140 for (n = 0; rmvattrs[n]; n++);
3141 rmva = calloc(2 * n + 1, sizeof(uint32_t));
3143 debugx(1, DBG_ERR, "malloc failed");
3145 for (p = rmva, i = 0; i < n; i++, p += 2)
3146 if (!vattrname2val(rmvattrs[i], p, p + 1))
3147 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
3148 freegconfmstr(rmvattrs);
3153 adda = list_create();
3155 debugx(1, DBG_ERR, "malloc failed");
3156 for (i = 0; addattrs[i]; i++) {
3157 a = extractattr(addattrs[i]);
3159 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
3160 if (!list_push(adda, a))
3161 debugx(1, DBG_ERR, "malloc failed");
3163 freegconfmstr(addattrs);
3167 moda = list_create();
3169 debugx(1, DBG_ERR, "malloc failed");
3170 for (i = 0; modattrs[i]; i++) {
3171 m = extractmodattr(modattrs[i]);
3173 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
3174 if (!list_push(moda, m))
3175 debugx(1, DBG_ERR, "malloc failed");
3177 freegconfmstr(modattrs);
3180 if (rma || rmva || adda || moda) {
3181 rewrite = malloc(sizeof(struct rewrite));
3183 debugx(1, DBG_ERR, "malloc failed");
3184 rewrite->removeattrs = rma;
3185 rewrite->removevendorattrs = rmva;
3186 rewrite->addattrs = adda;
3187 rewrite->modattrs = moda;
3190 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
3191 debugx(1, DBG_ERR, "malloc failed");
3192 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3195 int setttlattr(struct options *opts, char *defaultattr) {
3196 char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
3198 if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
3199 (opts->ttlattrtype[1] != -1 || opts->ttlattrtype[0] < 256))
3201 debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
3205 void freeclsrvconf(struct clsrvconf *conf) {
3211 free(conf->matchcertattr);
3212 if (conf->certcnregex)
3213 regfree(conf->certcnregex);
3214 if (conf->certuriregex)
3215 regfree(conf->certuriregex);
3216 free(conf->confrewritein);
3217 free(conf->confrewriteout);
3218 if (conf->rewriteusername) {
3219 if (conf->rewriteusername->regex)
3220 regfree(conf->rewriteusername->regex);
3221 free(conf->rewriteusername->replacement);
3222 free(conf->rewriteusername);
3224 free(conf->dynamiclookupcommand);
3225 free(conf->rewritein);
3226 free(conf->rewriteout);
3228 freeaddrinfo(conf->addrinfo);
3230 pthread_mutex_destroy(conf->lock);
3233 /* not touching ssl_ctx, clients and servers */
3237 int mergeconfstring(char **dst, char **src) {
3246 t = stringcopy(*dst, 0);
3248 debug(DBG_ERR, "malloc failed");
3256 /* assumes dst is a shallow copy */
3257 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3258 if (!mergeconfstring(&dst->name, &src->name) ||
3259 !mergeconfstring(&dst->host, &src->host) ||
3260 !mergeconfstring(&dst->port, &src->port) ||
3261 !mergeconfstring(&dst->secret, &src->secret) ||
3262 !mergeconfstring(&dst->tls, &src->tls) ||
3263 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3264 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
3265 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
3266 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3269 dst->pdef = src->pdef;
3270 dst->statusserver = src->statusserver;
3271 dst->certnamecheck = src->certnamecheck;
3272 if (src->retryinterval != 255)
3273 dst->retryinterval = src->retryinterval;
3274 if (src->retrycount != 255)
3275 dst->retrycount = src->retrycount;
3279 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3280 struct clsrvconf *conf;
3281 char *conftype = NULL, *rewriteinalias = NULL;
3282 long int dupinterval = LONG_MIN, addttl = LONG_MIN;
3284 debug(DBG_DBG, "confclient_cb called for %s", block);
3286 conf = malloc(sizeof(struct clsrvconf));
3288 debugx(1, DBG_ERR, "malloc failed");
3289 memset(conf, 0, sizeof(struct clsrvconf));
3290 conf->certnamecheck = 1;
3292 if (!getgenericconfig(cf, block,
3293 "type", CONF_STR, &conftype,
3294 "host", CONF_STR, &conf->host,
3295 "secret", CONF_STR, &conf->secret,
3296 "tls", CONF_STR, &conf->tls,
3297 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3298 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3299 "DuplicateInterval", CONF_LINT, &dupinterval,
3300 "addTTL", CONF_LINT, &addttl,
3301 "rewrite", CONF_STR, &rewriteinalias,
3302 "rewriteIn", CONF_STR, &conf->confrewritein,
3303 "rewriteOut", CONF_STR, &conf->confrewriteout,
3304 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
3307 debugx(1, DBG_ERR, "configuration error");
3309 conf->name = stringcopy(val, 0);
3311 conf->host = stringcopy(val, 0);
3312 if (!conf->name || !conf->host)
3313 debugx(1, DBG_ERR, "malloc failed");
3316 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3317 conf->type = protoname2int(conftype);
3318 conf->pdef = &protodefs[conf->type];
3319 if (!conf->pdef->name)
3320 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3323 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3324 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
3326 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3327 if (conf->matchcertattr && !addmatchcertattr(conf))
3328 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3331 if (dupinterval != LONG_MIN) {
3332 if (dupinterval < 0 || dupinterval > 255)
3333 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
3334 conf->dupinterval = (uint8_t)dupinterval;
3336 conf->dupinterval = conf->pdef->duplicateintervaldefault;
3338 if (addttl != LONG_MIN) {
3339 if (addttl < 1 || addttl > 255)
3340 debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
3341 conf->addttl = (uint8_t)addttl;
3344 if (!conf->confrewritein)
3345 conf->confrewritein = rewriteinalias;
3347 free(rewriteinalias);
3348 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
3349 if (conf->confrewriteout)
3350 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3352 if (conf->confrewriteusername) {
3353 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
3354 if (!conf->rewriteusername)
3355 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3358 if (!resolvepeer(conf, 0))
3359 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3361 if (!conf->secret) {
3362 if (!conf->pdef->secretdefault)
3363 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3364 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3366 debugx(1, DBG_ERR, "malloc failed");
3369 conf->lock = malloc(sizeof(pthread_mutex_t));
3371 debugx(1, DBG_ERR, "malloc failed");
3373 pthread_mutex_init(conf->lock, NULL);
3374 if (!list_push(clconfs, conf))
3375 debugx(1, DBG_ERR, "malloc failed");
3379 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3380 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3381 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
3382 if (!conf->tlsconf) {
3383 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3386 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3387 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3393 conf->port = stringcopy(conf->pdef->portdefault, 0);
3395 debug(DBG_ERR, "malloc failed");
3400 if (conf->retryinterval == 255)
3401 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3402 if (conf->retrycount == 255)
3403 conf->retrycount = protodefs[conf->type].retrycountdefault;
3405 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
3406 if (conf->confrewriteout)
3407 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3409 if (!conf->secret) {
3410 if (!conf->pdef->secretdefault) {
3411 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3414 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3415 if (!conf->secret) {
3416 debug(DBG_ERR, "malloc failed");
3421 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3422 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3428 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3429 struct clsrvconf *conf, *resconf;
3430 char *conftype = NULL, *rewriteinalias = NULL;
3431 long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
3433 debug(DBG_DBG, "confserver_cb called for %s", block);
3435 conf = malloc(sizeof(struct clsrvconf));
3437 debug(DBG_ERR, "malloc failed");
3440 memset(conf, 0, sizeof(struct clsrvconf));
3441 resconf = (struct clsrvconf *)arg;
3443 conf->statusserver = resconf->statusserver;
3444 conf->certnamecheck = resconf->certnamecheck;
3446 conf->certnamecheck = 1;
3448 if (!getgenericconfig(cf, block,
3449 "type", CONF_STR, &conftype,
3450 "host", CONF_STR, &conf->host,
3451 "port", CONF_STR, &conf->port,
3452 "secret", CONF_STR, &conf->secret,
3453 "tls", CONF_STR, &conf->tls,
3454 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3455 "addTTL", CONF_LINT, &addttl,
3456 "rewrite", CONF_STR, &rewriteinalias,
3457 "rewriteIn", CONF_STR, &conf->confrewritein,
3458 "rewriteOut", CONF_STR, &conf->confrewriteout,
3459 "StatusServer", CONF_BLN, &conf->statusserver,
3460 "RetryInterval", CONF_LINT, &retryinterval,
3461 "RetryCount", CONF_LINT, &retrycount,
3462 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3463 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3466 debug(DBG_ERR, "configuration error");
3470 conf->name = stringcopy(val, 0);
3472 debug(DBG_ERR, "malloc failed");
3476 conf->host = stringcopy(val, 0);
3478 debug(DBG_ERR, "malloc failed");
3484 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3485 conf->type = protoname2int(conftype);
3486 conf->pdef = &protodefs[conf->type];
3487 if (!conf->pdef->name) {
3488 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3494 if (!conf->confrewritein)
3495 conf->confrewritein = rewriteinalias;
3497 free(rewriteinalias);
3498 rewriteinalias = NULL;
3500 if (retryinterval != LONG_MIN) {
3501 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3502 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3505 conf->retryinterval = (uint8_t)retryinterval;
3507 conf->retryinterval = 255;
3509 if (retrycount != LONG_MIN) {
3510 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3511 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3514 conf->retrycount = (uint8_t)retrycount;
3516 conf->retrycount = 255;
3518 if (addttl != LONG_MIN) {
3519 if (addttl < 1 || addttl > 255) {
3520 debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
3523 conf->addttl = (uint8_t)addttl;
3527 if (!mergesrvconf(resconf, conf))
3531 if (conf->dynamiclookupcommand) {
3532 free(conf->dynamiclookupcommand);
3533 conf->dynamiclookupcommand = NULL;
3537 if (resconf || !conf->dynamiclookupcommand) {
3538 if (!compileserverconfig(conf, block))
3545 if (!list_push(srvconfs, conf)) {
3546 debug(DBG_ERR, "malloc failed");
3553 free(rewriteinalias);
3554 freeclsrvconf(conf);
3558 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3559 char **servers = NULL, **accservers = NULL, *msg = NULL;
3560 uint8_t accresp = 0;
3562 debug(DBG_DBG, "confrealm_cb called for %s", block);
3564 if (!getgenericconfig(cf, block,
3565 "server", CONF_MSTR, &servers,
3566 "accountingServer", CONF_MSTR, &accservers,
3567 "ReplyMessage", CONF_STR, &msg,
3568 "AccountingResponse", CONF_BLN, &accresp,
3571 debugx(1, DBG_ERR, "configuration error");
3573 addrealm(realms, val, servers, accservers, msg, accresp);
3577 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3579 long int expiry = LONG_MIN;
3581 debug(DBG_DBG, "conftls_cb called for %s", block);
3583 conf = malloc(sizeof(struct tls));
3585 debug(DBG_ERR, "conftls_cb: malloc failed");
3588 memset(conf, 0, sizeof(struct tls));
3590 if (!getgenericconfig(cf, block,
3591 "CACertificateFile", CONF_STR, &conf->cacertfile,
3592 "CACertificatePath", CONF_STR, &conf->cacertpath,
3593 "CertificateFile", CONF_STR, &conf->certfile,
3594 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3595 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3596 "CacheExpiry", CONF_LINT, &expiry,
3597 "CRLCheck", CONF_BLN, &conf->crlcheck,
3598 "PolicyOID", CONF_MSTR, &conf->policyoids,
3601 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3604 if (!conf->certfile || !conf->certkeyfile) {
3605 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3608 if (!conf->cacertfile && !conf->cacertpath) {
3609 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3612 if (expiry != LONG_MIN) {
3614 debug(DBG_ERR, "error in block %s, value of option CacheExpiry is %ld, may not be negative", val, expiry);
3617 conf->cacheexpiry = expiry;
3620 conf->name = stringcopy(val, 0);
3622 debug(DBG_ERR, "conftls_cb: malloc failed");
3626 if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
3627 debug(DBG_ERR, "conftls_cb: malloc failed");
3630 if (!tlsgetctx(RAD_TLS, conf))
3631 debug(DBG_ERR, "conftls_cb: error creating ctx for TLS block %s", val);
3632 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3636 free(conf->cacertfile);
3637 free(conf->cacertpath);
3638 free(conf->certfile);
3639 free(conf->certkeyfile);
3640 free(conf->certkeypwd);
3641 freegconfmstr(conf->policyoids);
3646 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3647 char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3649 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3651 if (!getgenericconfig(cf, block,
3652 "removeAttribute", CONF_MSTR, &rmattrs,
3653 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3654 "addAttribute", CONF_MSTR, &addattrs,
3655 "modifyAttribute", CONF_MSTR, &modattrs,
3658 debugx(1, DBG_ERR, "configuration error");
3659 addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3663 void getmainconfig(const char *configfile) {
3664 long int addttl = LONG_MIN, loglevel = LONG_MIN;
3665 struct gconffile *cfs;
3667 cfs = openconfigfile(configfile);
3668 memset(&options, 0, sizeof(options));
3670 clconfs = list_create();
3672 debugx(1, DBG_ERR, "malloc failed");
3674 srvconfs = list_create();
3676 debugx(1, DBG_ERR, "malloc failed");
3678 realms = list_create();
3680 debugx(1, DBG_ERR, "malloc failed");
3682 tlsconfs = hash_create();
3684 debugx(1, DBG_ERR, "malloc failed");
3686 rewriteconfs = hash_create();
3688 debugx(1, DBG_ERR, "malloc failed");
3690 if (!getgenericconfig(&cfs, NULL,
3691 "ListenUDP", CONF_MSTR, &options.listenargs[RAD_UDP],
3692 "ListenTCP", CONF_MSTR, &options.listenargs[RAD_TCP],
3693 "ListenTLS", CONF_MSTR, &options.listenargs[RAD_TLS],
3694 "ListenDTLS", CONF_MSTR, &options.listenargs[RAD_DTLS],
3695 "SourceUDP", CONF_STR, &options.sourcearg[RAD_UDP],
3696 "SourceTCP", CONF_STR, &options.sourcearg[RAD_TCP],
3697 "SourceTLS", CONF_STR, &options.sourcearg[RAD_TLS],
3698 "SourceDTLS", CONF_STR, &options.sourcearg[RAD_DTLS],
3699 "TTLAttribute", CONF_STR, &options.ttlattr,
3700 "addTTL", CONF_LINT, &addttl,
3701 "LogLevel", CONF_LINT, &loglevel,
3702 "LogDestination", CONF_STR, &options.logdestination,
3703 "LoopPrevention", CONF_BLN, &options.loopprevention,
3704 "Client", CONF_CBK, confclient_cb, NULL,
3705 "Server", CONF_CBK, confserver_cb, NULL,
3706 "Realm", CONF_CBK, confrealm_cb, NULL,
3707 "TLS", CONF_CBK, conftls_cb, NULL,
3708 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3711 debugx(1, DBG_ERR, "configuration error");
3713 if (loglevel != LONG_MIN) {
3714 if (loglevel < 1 || loglevel > 4)
3715 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3716 options.loglevel = (uint8_t)loglevel;
3718 if (addttl != LONG_MIN) {
3719 if (addttl < 1 || addttl > 255)
3720 debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3721 options.addttl = (uint8_t)addttl;
3723 if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3724 debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3727 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3730 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3733 *configfile = optarg;
3736 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3737 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3738 *loglevel = *optarg - '0';
3747 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3752 if (!(argc - optind))
3756 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3760 int daemon(int a, int b) {
3768 for (i = 0; i < 3; i++) {
3770 open("/dev/null", O_RDWR);
3776 void *sighandler(void *arg) {
3781 sigemptyset(&sigset);
3782 sigaddset(&sigset, SIGPIPE);
3783 sigwait(&sigset, &sig);
3784 /* only get SIGPIPE right now, so could simplify below code */
3787 /* completely ignoring this */
3790 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3793 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3798 int main(int argc, char **argv) {
3801 struct list_node *entry;
3802 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3803 char *configfile = NULL;
3804 struct clsrvconf *srvconf;
3807 debug_init("radsecproxy");
3808 debug_set_level(DEBUG_LEVEL);
3810 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3812 debug_set_level(loglevel);
3813 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3815 options.loglevel = loglevel;
3816 else if (options.loglevel)
3817 debug_set_level(options.loglevel);
3819 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3820 free(options.logdestination);
3822 if (!list_first(clconfs))
3823 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3824 if (!list_first(realms))
3825 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3828 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3830 if (!foreground && (daemon(0, 0) < 0))
3831 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3833 debug_timestamp_on();
3834 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3836 sigemptyset(&sigset);
3837 /* exit on all but SIGPIPE, ignore more? */
3838 sigaddset(&sigset, SIGPIPE);
3839 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3840 pthread_create(&sigth, NULL, sighandler, NULL);
3842 memset(srcprotores, 0, sizeof(srcprotores));
3843 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3844 srvconf = (struct clsrvconf *)entry->data;
3845 if (srvconf->dynamiclookupcommand)
3847 if (!addserver(srvconf))
3848 debugx(1, DBG_ERR, "failed to add server");
3849 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3850 (void *)(srvconf->servers)))
3851 debugx(1, DBG_ERR, "pthread_create failed");
3854 for (i = 0; protodefs[i].name; i++) {
3855 if (protodefs[i].freesrcprotores && srcprotores[i]) {
3856 freeaddrinfo(srcprotores[i]);
3857 srcprotores[i] = NULL;
3859 if (protodefs[i].initextra)
3860 protodefs[i].initextra();
3861 if (find_clconf_type(i, NULL))
3862 createlisteners(i, options.listenargs[i]);
3865 /* just hang around doing nothing, anything to do here? */