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 pthread_mutex_t *ssl_locks = NULL;
86 static long *ssl_lock_count;
90 /* minimum required declarations to avoid reordering code */
91 struct realm *adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
92 int dynamicconfig(struct server *server);
93 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
94 void freerealm(struct realm *realm);
95 void freeclsrvconf(struct clsrvconf *conf);
96 void freerq(struct request *rq);
97 void freerqoutdata(struct rqout *rqout);
98 void rmclientrq(struct request *rq, uint8_t id);
100 static const struct protodefs protodefs[] = {
101 { "udp", /* UDP, assuming RAD_UDP defined as 0 */
102 NULL, /* secretdefault */
103 SOCK_DGRAM, /* socktype */
104 "1812", /* portdefault */
105 REQUEST_RETRY_COUNT, /* retrycountdefault */
106 10, /* retrycountmax */
107 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
108 60, /* retryintervalmax */
109 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
110 udpserverrd, /* listener */
111 NULL, /* connecter */
112 NULL, /* clientconnreader */
113 clientradputudp, /* clientradput */
114 addclientudp, /* addclient */
115 addserverextraudp, /* addserverextra */
116 udpsetsrcres, /* setsrcres */
117 initextraudp /* initextra */
119 { "tls", /* TLS, assuming RAD_TLS defined as 1 */
120 "mysecret", /* secretdefault */
121 SOCK_STREAM, /* socktype */
122 "2083", /* portdefault */
123 0, /* retrycountdefault */
124 0, /* retrycountmax */
125 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
126 60, /* retryintervalmax */
127 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
128 tlslistener, /* listener */
129 tlsconnect, /* connecter */
130 tlsclientrd, /* clientconnreader */
131 clientradputtls, /* clientradput */
132 NULL, /* addclient */
133 NULL, /* addserverextra */
134 tlssetsrcres, /* setsrcres */
137 { "tcp", /* TCP, assuming RAD_TCP defined as 2 */
138 NULL, /* secretdefault */
139 SOCK_STREAM, /* socktype */
140 "1812", /* portdefault */
141 0, /* retrycountdefault */
142 0, /* retrycountmax */
143 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
144 60, /* retryintervalmax */
145 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
146 tcplistener, /* listener */
147 tcpconnect, /* connecter */
148 tcpclientrd, /* clientconnreader */
149 clientradputtcp, /* clientradput */
150 NULL, /* addclient */
151 NULL, /* addserverextra */
152 tcpsetsrcres, /* setsrcres */
155 { "dtls", /* DTLS, assuming RAD_DTLS defined as 3 */
156 "mysecret", /* secretdefault */
157 SOCK_DGRAM, /* socktype */
158 "2083", /* portdefault */
159 REQUEST_RETRY_COUNT, /* retrycountdefault */
160 10, /* retrycountmax */
161 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
162 60, /* retryintervalmax */
163 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
164 udpdtlsserverrd, /* listener */
165 dtlsconnect, /* connecter */
166 dtlsclientrd, /* clientconnreader */
167 clientradputdtls, /* clientradput */
168 NULL, /* addclient */
169 addserverextradtls, /* addserverextra */
170 dtlssetsrcres, /* setsrcres */
171 initextradtls /* initextra */
173 { NULL, NULL, 0, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
177 uint8_t protoname2int(const char *name) {
180 for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
184 /* callbacks for making OpenSSL thread safe */
185 unsigned long ssl_thread_id() {
186 return (unsigned long)pthread_self();
189 void ssl_locking_callback(int mode, int type, const char *file, int line) {
190 if (mode & CRYPTO_LOCK) {
191 pthread_mutex_lock(&ssl_locks[type]);
192 ssl_lock_count[type]++;
194 pthread_mutex_unlock(&ssl_locks[type]);
197 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
198 int pwdlen = strlen(userdata);
199 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
201 memcpy(buf, userdata, pwdlen);
205 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
210 err_cert = X509_STORE_CTX_get_current_cert(ctx);
211 err = X509_STORE_CTX_get_error(ctx);
212 depth = X509_STORE_CTX_get_error_depth(ctx);
214 if (depth > MAX_CERT_DEPTH) {
216 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
217 X509_STORE_CTX_set_error(ctx, err);
222 buf = X509_NAME_oneline(X509_get_subject_name(err_cert), NULL, 0);
223 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf ? buf : "");
228 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
230 buf = X509_NAME_oneline(X509_get_issuer_name(err_cert), NULL, 0);
232 debug(DBG_WARN, "\tIssuer=%s", buf);
238 case X509_V_ERR_CERT_NOT_YET_VALID:
239 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
240 debug(DBG_WARN, "\tCertificate not yet valid");
242 case X509_V_ERR_CERT_HAS_EXPIRED:
243 debug(DBG_WARN, "Certificate has expired");
245 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
246 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
248 case X509_V_ERR_NO_EXPLICIT_POLICY:
249 debug(DBG_WARN, "No Explicit Certificate Policy");
254 printf("certificate verify returns %d\n", ok);
259 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
260 struct addrinfo hints, *addrinfo, *res;
264 slash = conf->host ? strchr(conf->host, '/') : NULL;
268 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
272 if (*s < '0' || *s > '9') {
273 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
276 plen = atoi(slash + 1);
277 if (plen < 0 || plen > 128) {
278 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
283 memset(&hints, 0, sizeof(hints));
284 hints.ai_socktype = conf->pdef->socktype;
285 hints.ai_family = AF_UNSPEC;
286 hints.ai_flags = ai_flags;
287 if (!conf->host && !conf->port) {
288 /* getaddrinfo() doesn't like host and port to be NULL */
289 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
290 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
293 for (res = addrinfo; res; res = res->ai_next)
294 port_set(res->ai_addr, 0);
297 hints.ai_flags |= AI_NUMERICHOST;
298 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
299 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
304 switch (addrinfo->ai_family) {
307 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
308 freeaddrinfo(addrinfo);
315 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
316 freeaddrinfo(addrinfo);
319 conf->prefixlen = (uint8_t)plen;
321 conf->prefixlen = 255;
324 freeaddrinfo(conf->addrinfo);
325 conf->addrinfo = addrinfo;
329 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
334 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
338 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
340 debugx(1, DBG_ERR, "no ] matching initial [");
344 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
347 debugx(1, DBG_ERR, "missing host/address");
349 conf->host = stringcopy(field, p - field);
352 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
353 debugx(1, DBG_ERR, "unexpected character after ]");
356 /* port number or service name is specified */;
358 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
360 debugx(1, DBG_ERR, "syntax error, : but no following port");
361 conf->port = stringcopy(field, p - field);
363 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
367 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
368 struct clsrvconf *conf;
370 conf = malloc(sizeof(struct clsrvconf));
372 debugx(1, DBG_ERR, "malloc failed");
373 memset(conf, 0, sizeof(struct clsrvconf));
375 conf->pdef = &protodefs[conf->type];
377 parsehostport(lconf, conf, default_port);
378 if (!strcmp(conf->host, "*")) {
383 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
384 if (!resolvepeer(conf, AI_PASSIVE))
385 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
389 void freeclsrvres(struct clsrvconf *res) {
393 freeaddrinfo(res->addrinfo);
397 struct addrinfo *resolve_hostport_addrinfo(uint8_t type, char *hostport) {
399 struct clsrvconf *res;
401 res = resolve_hostport(type, hostport, NULL);
403 res->addrinfo = NULL;
408 /* returns 1 if the len first bits are equal, else 0 */
409 int prefixmatch(void *a1, void *a2, uint8_t len) {
410 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
411 uint8_t r, l = len / 8;
412 if (l && memcmp(a1, a2, l))
417 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
420 /* returns next config with matching address, or NULL */
421 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
422 struct sockaddr_in6 *sa6 = NULL;
423 struct in_addr *a4 = NULL;
424 struct addrinfo *res;
425 struct list_node *entry;
426 struct clsrvconf *conf;
428 if (addr->sa_family == AF_INET6) {
429 sa6 = (struct sockaddr_in6 *)addr;
430 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
431 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
435 a4 = &((struct sockaddr_in *)addr)->sin_addr;
437 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
438 conf = (struct clsrvconf *)entry->data;
439 if (conf->type == type) {
440 if (conf->prefixlen == 255) {
441 for (res = conf->addrinfo; res; res = res->ai_next)
442 if ((a4 && res->ai_family == AF_INET &&
443 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
444 (sa6 && res->ai_family == AF_INET6 &&
445 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
451 res = conf->addrinfo;
453 ((a4 && res->ai_family == AF_INET &&
454 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
455 (sa6 && res->ai_family == AF_INET6 &&
456 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
467 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
468 return find_conf(type, addr, clconfs, cur);
471 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
472 return find_conf(type, addr, srvconfs, cur);
475 /* returns next config of given type, or NULL */
476 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
477 struct list_node *entry;
478 struct clsrvconf *conf;
480 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
481 conf = (struct clsrvconf *)entry->data;
482 if (conf->type == type) {
491 struct queue *newqueue() {
494 q = malloc(sizeof(struct queue));
496 debugx(1, DBG_ERR, "malloc failed");
497 q->entries = list_create();
499 debugx(1, DBG_ERR, "malloc failed");
500 pthread_mutex_init(&q->mutex, NULL);
501 pthread_cond_init(&q->cond, NULL);
505 void removequeue(struct queue *q) {
506 struct list_node *entry;
510 pthread_mutex_lock(&q->mutex);
511 for (entry = list_first(q->entries); entry; entry = list_next(entry))
512 freerq((struct request *)entry);
513 list_destroy(q->entries);
514 pthread_cond_destroy(&q->cond);
515 pthread_mutex_unlock(&q->mutex);
516 pthread_mutex_destroy(&q->mutex);
520 void freebios(struct queue *q) {
523 pthread_mutex_lock(&q->mutex);
524 while ((bio = (BIO *)list_shift(q->entries)))
526 pthread_mutex_unlock(&q->mutex);
530 struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
531 struct client *new = malloc(sizeof(struct client));
534 debug(DBG_ERR, "malloc failed");
539 pthread_mutex_lock(conf->lock);
540 if (!conf->clients) {
541 conf->clients = list_create();
542 if (!conf->clients) {
544 pthread_mutex_unlock(conf->lock);
545 debug(DBG_ERR, "malloc failed");
550 memset(new, 0, sizeof(struct client));
552 if (conf->pdef->addclient)
553 conf->pdef->addclient(new);
555 new->replyq = newqueue();
556 list_push(conf->clients, new);
558 pthread_mutex_unlock(conf->lock);
562 void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
563 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
566 pthread_mutex_lock(&lock);
568 pthread_mutex_unlock(&lock);
571 void removeclientrqs(struct client *client) {
576 removeclientrqs_sendrq_freeserver_lock(1);
577 for (i = 0; i < MAX_REQUESTS; i++) {
582 rqout = rq->to->requests + rq->newid;
583 pthread_mutex_lock(rqout->lock);
584 if (rqout->rq == rq) /* still pointing to our request */
585 freerqoutdata(rqout);
586 pthread_mutex_unlock(rqout->lock);
590 removeclientrqs_sendrq_freeserver_lock(0);
593 void removelockedclient(struct client *client) {
594 struct clsrvconf *conf;
598 removeclientrqs(client);
599 removequeue(client->replyq);
600 list_removedata(conf->clients, client);
606 void removeclient(struct client *client) {
607 struct clsrvconf *conf;
613 pthread_mutex_lock(conf->lock);
614 removelockedclient(client);
615 pthread_mutex_unlock(conf->lock);
618 void freeserver(struct server *server, uint8_t destroymutex) {
619 struct rqout *rqout, *end;
624 removeclientrqs_sendrq_freeserver_lock(1);
625 if (server->requests) {
626 rqout = server->requests;
627 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
629 rqout->rq->to = NULL;
630 freerqoutdata(rqout);
631 pthread_mutex_destroy(rqout->lock);
634 free(server->requests);
637 freebios(server->rbios);
638 free(server->dynamiclookuparg);
640 SSL_free(server->ssl);
642 pthread_mutex_destroy(&server->lock);
643 pthread_cond_destroy(&server->newrq_cond);
644 pthread_mutex_destroy(&server->newrq_mutex);
646 removeclientrqs_sendrq_freeserver_lock(0);
650 int addserver(struct clsrvconf *conf) {
655 debug(DBG_ERR, "addserver: currently works with just one server per conf");
658 conf->servers = malloc(sizeof(struct server));
659 if (!conf->servers) {
660 debug(DBG_ERR, "malloc failed");
663 memset(conf->servers, 0, sizeof(struct server));
664 conf->servers->conf = conf;
667 if (type == RAD_DTLS)
668 conf->servers->rbios = newqueue();
670 conf->pdef->setsrcres(options.sourcearg[type]);
672 conf->servers->sock = -1;
673 if (conf->pdef->addserverextra)
674 conf->pdef->addserverextra(conf);
676 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
677 if (!conf->servers->requests) {
678 debug(DBG_ERR, "malloc failed");
681 for (i = 0; i < MAX_REQUESTS; i++) {
682 conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
683 if (!conf->servers->requests[i].lock) {
684 debug(DBG_ERR, "malloc failed");
687 if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
688 debug(DBG_ERR, "mutex init failed");
689 free(conf->servers->requests[i].lock);
690 conf->servers->requests[i].lock = NULL;
694 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
695 debug(DBG_ERR, "mutex init failed");
698 conf->servers->newrq = 0;
699 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
700 debug(DBG_ERR, "mutex init failed");
701 pthread_mutex_destroy(&conf->servers->lock);
704 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
705 debug(DBG_ERR, "mutex init failed");
706 pthread_mutex_destroy(&conf->servers->newrq_mutex);
707 pthread_mutex_destroy(&conf->servers->lock);
714 freeserver(conf->servers, 0);
715 conf->servers = NULL;
719 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
720 int loc, i, l, n, r = 0;
723 STACK_OF(GENERAL_NAME) *alt;
726 debug(DBG_DBG, "subjectaltnameaddr");
728 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
732 ex = X509_get_ext(cert, loc);
733 alt = X509V3_EXT_d2i(ex);
737 n = sk_GENERAL_NAME_num(alt);
738 for (i = 0; i < n; i++) {
739 gn = sk_GENERAL_NAME_value(alt, i);
740 if (gn->type != GEN_IPADD)
743 v = (char *)ASN1_STRING_data(gn->d.ia5);
744 l = ASN1_STRING_length(gn->d.ia5);
745 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
746 && !memcmp(v, &addr, l)) {
751 GENERAL_NAMES_free(alt);
755 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
762 nm = X509_get_subject_name(cert);
765 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
768 e = X509_NAME_get_entry(nm, loc);
769 t = X509_NAME_ENTRY_get_data(e);
770 v = (char *) ASN1_STRING_data(t);
771 l = ASN1_STRING_length(t);
775 if (l == strlen(exact) && !strncasecmp(exact, v, l))
778 s = stringcopy((char *)v, l);
780 debug(DBG_ERR, "malloc failed");
783 if (regexec(regex, s, 0, NULL, 0)) {
794 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
795 int loc, i, l, n, r = 0;
798 STACK_OF(GENERAL_NAME) *alt;
801 debug(DBG_DBG, "subjectaltnameregexp");
803 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
807 ex = X509_get_ext(cert, loc);
808 alt = X509V3_EXT_d2i(ex);
812 n = sk_GENERAL_NAME_num(alt);
813 for (i = 0; i < n; i++) {
814 gn = sk_GENERAL_NAME_value(alt, i);
815 if (gn->type != type)
818 v = (char *)ASN1_STRING_data(gn->d.ia5);
819 l = ASN1_STRING_length(gn->d.ia5);
823 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
826 if (memcmp(v, exact, l))
829 s = stringcopy((char *)v, l);
831 debug(DBG_ERR, "malloc failed");
834 if (regexec(regex, s, 0, NULL, 0)) {
843 GENERAL_NAMES_free(alt);
847 X509 *verifytlscert(SSL *ssl) {
851 if (SSL_get_verify_result(ssl) != X509_V_OK) {
852 debug(DBG_ERR, "verifytlscert: basic validation failed");
853 while ((error = ERR_get_error()))
854 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
858 cert = SSL_get_peer_certificate(ssl);
860 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
864 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
866 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
867 struct in6_addr addr;
869 if (conf->certnamecheck && conf->prefixlen == 255) {
870 if (inet_pton(AF_INET, conf->host, &addr))
872 else if (inet_pton(AF_INET6, conf->host, &addr))
875 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
878 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
881 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
883 if (!cnregexp(cert, conf->host, NULL)) {
884 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
887 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
890 if (conf->certcnregex) {
891 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
892 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
895 debug(DBG_DBG, "verifyconfcert: CN matching regex");
897 if (conf->certuriregex) {
898 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
899 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
902 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
907 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
909 if (ATTRTYPE(attrs) == type)
911 length -= ATTRLEN(attrs);
912 attrs += ATTRLEN(attrs);
917 struct request *newrqref(struct request *rq) {
923 void freerq(struct request *rq) {
926 debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
929 if (rq->origusername)
930 free(rq->origusername);
936 radmsg_free(rq->msg);
940 void freerqoutdata(struct rqout *rqout) {
944 if (rqout->rq->buf) {
945 free(rqout->rq->buf);
946 rqout->rq->buf = NULL;
952 memset(&rqout->expiry, 0, sizeof(struct timeval));
955 void sendrq(struct request *rq) {
959 removeclientrqs_sendrq_freeserver_lock(1);
964 start = to->conf->statusserver ? 1 : 0;
965 pthread_mutex_lock(&to->newrq_mutex);
966 if (start && rq->msg->code == RAD_Status_Server) {
967 pthread_mutex_lock(to->requests[0].lock);
968 if (to->requests[0].rq) {
969 pthread_mutex_unlock(to->requests[0].lock);
970 debug(DBG_WARN, "sendrq: status server already in queue, dropping request");
977 /* might simplify if only try nextid, might be ok */
978 for (i = to->nextid; i < MAX_REQUESTS; i++) {
979 if (!to->requests[i].rq) {
980 pthread_mutex_lock(to->requests[i].lock);
981 if (!to->requests[i].rq)
983 pthread_mutex_unlock(to->requests[i].lock);
986 if (i == MAX_REQUESTS) {
987 for (i = start; i < to->nextid; i++) {
988 if (!to->requests[i].rq) {
989 pthread_mutex_lock(to->requests[i].lock);
990 if (!to->requests[i].rq)
992 pthread_mutex_unlock(to->requests[i].lock);
995 if (i == to->nextid) {
996 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
1001 rq->newid = (uint8_t)i;
1002 rq->msg->id = (uint8_t)i;
1003 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
1005 pthread_mutex_unlock(to->requests[i].lock);
1006 debug(DBG_ERR, "sendrq: radmsg2buf failed");
1010 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1011 to->requests[i].rq = rq;
1012 pthread_mutex_unlock(to->requests[i].lock);
1013 if (i >= start) /* i is not reserved for statusserver */
1018 debug(DBG_DBG, "sendrq: signalling client writer");
1019 pthread_cond_signal(&to->newrq_cond);
1022 pthread_mutex_unlock(&to->newrq_mutex);
1023 removeclientrqs_sendrq_freeserver_lock(0);
1028 rmclientrq(rq, rq->msg->id);
1030 pthread_mutex_unlock(&to->newrq_mutex);
1031 removeclientrqs_sendrq_freeserver_lock(0);
1034 void sendreply(struct request *rq) {
1036 struct client *to = rq->from;
1039 rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
1040 radmsg_free(rq->msg);
1042 if (!rq->replybuf) {
1044 debug(DBG_ERR, "sendreply: radmsg2buf failed");
1048 pthread_mutex_lock(&to->replyq->mutex);
1049 first = list_first(to->replyq->entries) == NULL;
1051 if (!list_push(to->replyq->entries, rq)) {
1052 pthread_mutex_unlock(&to->replyq->mutex);
1054 debug(DBG_ERR, "sendreply: malloc failed");
1059 debug(DBG_DBG, "signalling server writer");
1060 pthread_cond_signal(&to->replyq->cond);
1062 pthread_mutex_unlock(&to->replyq->mutex);
1065 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1066 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1067 static unsigned char first = 1;
1068 static EVP_MD_CTX mdctx;
1069 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1070 unsigned int md_len;
1071 uint8_t i, offset = 0, out[128];
1073 pthread_mutex_lock(&lock);
1075 EVP_MD_CTX_init(&mdctx);
1081 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1082 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1083 !EVP_DigestUpdate(&mdctx, input, 16) ||
1084 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1086 pthread_mutex_unlock(&lock);
1089 for (i = 0; i < 16; i++)
1090 out[offset + i] = hash[i] ^ in[offset + i];
1091 input = out + offset - 16;
1096 memcpy(in, out, len);
1097 pthread_mutex_unlock(&lock);
1101 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1102 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1103 static unsigned char first = 1;
1104 static EVP_MD_CTX mdctx;
1105 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1106 unsigned int md_len;
1107 uint8_t i, offset = 0, out[128];
1109 pthread_mutex_lock(&lock);
1111 EVP_MD_CTX_init(&mdctx);
1117 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1118 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1119 !EVP_DigestUpdate(&mdctx, input, 16) ||
1120 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1122 pthread_mutex_unlock(&lock);
1125 for (i = 0; i < 16; i++)
1126 out[offset + i] = hash[i] ^ in[offset + i];
1127 input = in + offset;
1132 memcpy(in, out, len);
1133 pthread_mutex_unlock(&lock);
1137 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1138 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1139 static unsigned char first = 1;
1140 static EVP_MD_CTX mdctx;
1141 unsigned char hash[EVP_MAX_MD_SIZE];
1142 unsigned int md_len;
1145 pthread_mutex_lock(&lock);
1147 EVP_MD_CTX_init(&mdctx);
1152 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1153 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1154 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1157 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1158 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1159 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1160 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1161 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1162 pthread_mutex_unlock(&lock);
1167 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1170 for (i = 0; i < 16; i++)
1173 for (offset = 16; offset < len; offset += 16) {
1175 printf("text + offset - 16 c(%d): ", offset / 16);
1176 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1178 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1179 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1180 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1181 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1183 pthread_mutex_unlock(&lock);
1187 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1190 for (i = 0; i < 16; i++)
1191 text[offset + i] ^= hash[i];
1195 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1198 pthread_mutex_unlock(&lock);
1202 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1203 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1204 static unsigned char first = 1;
1205 static EVP_MD_CTX mdctx;
1206 unsigned char hash[EVP_MAX_MD_SIZE];
1207 unsigned int md_len;
1211 pthread_mutex_lock(&lock);
1213 EVP_MD_CTX_init(&mdctx);
1218 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1219 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1220 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1223 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1224 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1225 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1226 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1227 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1228 pthread_mutex_unlock(&lock);
1233 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1236 for (i = 0; i < 16; i++)
1237 plain[i] = text[i] ^ hash[i];
1239 for (offset = 16; offset < len; offset += 16) {
1241 printf("text + offset - 16 c(%d): ", offset / 16);
1242 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1244 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1245 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1246 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1247 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1249 pthread_mutex_unlock(&lock);
1253 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1256 for (i = 0; i < 16; i++)
1257 plain[offset + i] = text[offset + i] ^ hash[i];
1260 memcpy(text, plain, len);
1262 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1265 pthread_mutex_unlock(&lock);
1269 struct realm *newrealmref(struct realm *r) {
1275 /* returns with lock on realm */
1276 struct realm *id2realm(struct list *realmlist, char *id) {
1277 struct list_node *entry;
1278 struct realm *realm, *subrealm;
1280 /* need to do locking for subrealms and check subrealm timers */
1281 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1282 realm = (struct realm *)entry->data;
1283 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1284 pthread_mutex_lock(&realm->mutex);
1285 if (realm->subrealms) {
1286 subrealm = id2realm(realm->subrealms, id);
1288 pthread_mutex_unlock(&realm->mutex);
1292 return newrealmref(realm);
1298 /* helper function, only used by removeserversubrealms() */
1299 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1300 struct list_node *entry, *entry2;
1301 struct realm *realm;
1303 for (entry = list_first(realmlist); entry;) {
1304 realm = newrealmref((struct realm *)entry->data);
1305 pthread_mutex_lock(&realm->mutex);
1306 entry = list_next(entry);
1308 if (realm->srvconfs) {
1309 for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
1310 if (entry2->data == srv)
1312 list_removedata(realm->srvconfs, srv);
1313 if (!list_first(realm->srvconfs)) {
1314 list_destroy(realm->srvconfs);
1315 realm->srvconfs = NULL;
1318 if (realm->accsrvconfs) {
1319 for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
1320 if (entry2->data == srv)
1322 list_removedata(realm->accsrvconfs, srv);
1323 if (!list_first(realm->accsrvconfs)) {
1324 list_destroy(realm->accsrvconfs);
1325 realm->accsrvconfs = NULL;
1329 /* remove subrealm if no servers */
1330 if (!realm->srvconfs && !realm->accsrvconfs)
1331 list_removedata(realmlist, realm);
1333 pthread_mutex_unlock(&realm->mutex);
1338 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1339 struct list_node *entry;
1340 struct realm *realm;
1342 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1343 realm = (struct realm *)entry->data;
1344 pthread_mutex_lock(&realm->mutex);
1345 if (realm->subrealms) {
1346 _internal_removeserversubrealms(realm->subrealms, srv);
1347 if (!list_first(realm->subrealms)) {
1348 list_destroy(realm->subrealms);
1349 realm->subrealms = NULL;
1352 pthread_mutex_unlock(&realm->mutex);
1356 int attrvalidate(unsigned char *attrs, int length) {
1357 while (length > 1) {
1358 if (ATTRLEN(attrs) < 2) {
1359 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1362 length -= ATTRLEN(attrs);
1364 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1367 attrs += ATTRLEN(attrs);
1370 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1374 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1375 if (len < 16 || len > 128 || len % 16) {
1376 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1380 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1381 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1385 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1387 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1388 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1394 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1397 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1398 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1401 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
1402 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1408 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1409 char *oldsecret, char *newsecret) {
1410 unsigned char *attr;
1412 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1413 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1414 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
1420 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1424 for (; attrs[0]; attrs += 2)
1425 if (attrs[0] == vendor && attrs[1] == subattr)
1430 /* returns 1 if entire element is to be removed, else 0 */
1431 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
1432 uint8_t alen, sublen;
1436 if (!removevendorattrs)
1439 memcpy(&vendor, attr->v, 4);
1440 vendor = ntohl(vendor);
1441 while (*removevendorattrs && *removevendorattrs != vendor)
1442 removevendorattrs += 2;
1443 if (!*removevendorattrs)
1446 if (findvendorsubattr(removevendorattrs, vendor, -1))
1447 return 1; /* remove entire vendor attribute */
1449 sublen = attr->l - 4;
1450 subattrs = attr->v + 4;
1452 if (!attrvalidate(subattrs, sublen)) {
1453 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1457 while (sublen > 1) {
1458 alen = ATTRLEN(subattrs);
1460 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1461 memmove(subattrs, subattrs + alen, sublen);
1469 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
1470 struct list_node *n, *p;
1474 n = list_first(msg->attrs);
1476 attr = (struct tlv *)n->data;
1477 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
1478 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
1479 list_removedata(msg->attrs, attr);
1481 n = p ? list_next(p) : list_first(msg->attrs);
1488 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
1489 struct list_node *n;
1492 for (n = list_first(addattrs); n; n = list_next(n)) {
1493 a = copytlv((struct tlv *)n->data);
1496 if (!radmsg_add(msg, a)) {
1504 int resizeattr(struct tlv *attr, uint8_t newlen) {
1507 if (newlen != attr->l) {
1508 newv = realloc(attr->v, newlen);
1517 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1518 size_t nmatch = 10, reslen = 0, start = 0;
1519 regmatch_t pmatch[10], *pfield;
1523 in = stringcopy((char *)attr->v, attr->l);
1527 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1532 out = modattr->replacement;
1534 for (i = start; out[i]; i++) {
1535 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1536 pfield = &pmatch[out[i + 1] - '0'];
1537 if (pfield->rm_so >= 0) {
1538 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1544 reslen += i - start;
1546 debug(DBG_WARN, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1551 if (!resizeattr(attr, reslen)) {
1558 for (i = start; out[i]; i++) {
1559 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1560 pfield = &pmatch[out[i + 1] - '0'];
1561 if (pfield->rm_so >= 0) {
1562 memcpy(attr->v + reslen, out + start, i - start);
1563 reslen += i - start;
1564 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1565 reslen += pfield->rm_eo - pfield->rm_so;
1572 memcpy(attr->v + reslen, out + start, i - start);
1576 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1577 struct list_node *n, *m;
1579 for (n = list_first(msg->attrs); n; n = list_next(n))
1580 for (m = list_first(modattrs); m; m = list_next(m))
1581 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1582 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1587 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1590 if (rewrite->removeattrs || rewrite->removevendorattrs)
1591 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1592 if (rewrite->addattrs && !dorewriteadd(msg, rewrite->addattrs))
1594 if (rewrite->modattrs && !dorewritemod(msg, rewrite->modattrs))
1599 int rewriteusername(struct request *rq, struct tlv *attr) {
1600 char *orig = (char *)tlv2str(attr);
1601 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1605 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1606 rq->origusername = (char *)orig;
1612 int addvendorattr(struct radmsg *msg, uint32_t vendor, struct tlv *attr) {
1619 vendor = htonl(vendor);
1620 memcpy(v, &vendor, 4);
1621 tlv2buf(v + 4, attr);
1623 vattr = maketlv(RAD_Attr_Vendor_Specific, l, v);
1624 if (vattr && radmsg_add(msg, vattr))
1631 void addttlattr(struct radmsg *msg, uint32_t *attrtype, uint8_t addttl) {
1638 if (attrtype[1] == -1) { /* not vendor */
1639 attr = maketlv(attrtype[0], 4, ttl);
1640 if (attr && !radmsg_add(msg, attr))
1643 attr = maketlv(attrtype[1], 4, ttl);
1645 addvendorattr(msg, attrtype[0], attr);
1651 int decttl(uint8_t l, uint8_t *v) {
1658 while (i >= 0 && !v[i])
1662 for (i--; i >= 0 && !v[i]; i--);
1671 /* returns -1 if no ttl, 0 if exceeded, 1 if ok */
1672 int checkttl(struct radmsg *msg, uint32_t *attrtype) {
1673 uint8_t alen, *subattrs;
1675 struct list_node *node;
1679 if (attrtype[1] == -1) { /* not vendor */
1680 attr = radmsg_gettype(msg, attrtype[0]);
1682 return decttl(attr->l, attr->v);
1684 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1685 attr = (struct tlv *)node->data;
1686 if (attr->t != RAD_Attr_Vendor_Specific || attr->l <= 4)
1688 memcpy(&vendor, attr->v, 4);
1689 if (ntohl(vendor) != attrtype[0])
1691 sublen = attr->l - 4;
1692 subattrs = attr->v + 4;
1693 if (!attrvalidate(subattrs, sublen))
1695 while (sublen > 1) {
1696 if (ATTRTYPE(subattrs) == attrtype[1])
1697 return decttl(ATTRVALLEN(subattrs), ATTRVAL(subattrs));
1698 alen = ATTRLEN(subattrs);
1706 const char *radmsgtype2string(uint8_t code) {
1707 static const char *rad_msg_names[] = {
1708 "", "Access-Request", "Access-Accept", "Access-Reject",
1709 "Accounting-Request", "Accounting-Response", "", "",
1710 "", "", "", "Access-Challenge",
1711 "Status-Server", "Status-Client"
1713 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1716 void char2hex(char *h, unsigned char c) {
1717 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1718 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1719 h[0] = hexdigits[c / 16];
1720 h[1] = hexdigits[c % 16];
1724 uint8_t *radattr2ascii(struct tlv *attr) {
1732 for (i = 0; i < attr->l; i++)
1733 if (attr->v[i] < 32 || attr->v[i] > 126)
1736 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1743 for (i = 0; i < attr->l; i++)
1744 if (attr->v[i] < 32 || attr->v[i] > 126) {
1746 char2hex((char *)d, attr->v[i]);
1754 void acclog(struct radmsg *msg, char *host) {
1758 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1760 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1763 username = radattr2ascii(attr);
1765 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1770 void respond(struct request *rq, uint8_t code, char *message) {
1774 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1776 debug(DBG_ERR, "respond: malloc failed");
1779 if (message && *message) {
1780 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1781 if (!attr || !radmsg_add(msg, attr)) {
1784 debug(DBG_ERR, "respond: malloc failed");
1789 radmsg_free(rq->msg);
1791 debug(DBG_DBG, "respond: sending %s to %s", radmsgtype2string(msg->code), rq->from->conf->host);
1792 sendreply(newrqref(rq));
1795 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1796 struct list_node *entry;
1797 struct clsrvconf *server, *best = NULL, *first = NULL;
1799 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1800 server = (struct clsrvconf *)entry->data;
1801 if (!server->servers)
1805 if (!server->servers->connectionok)
1807 if (!server->servers->lostrqs)
1813 if (server->servers->lostrqs < best->servers->lostrqs)
1816 return best ? best : first;
1819 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1820 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1821 struct clsrvconf *srvconf;
1822 struct realm *subrealm;
1823 struct server *server = NULL;
1824 char *id = (char *)tlv2str(username);
1828 /* returns with lock on realm */
1829 *realm = id2realm(realms, id);
1832 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1833 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1836 server = srvconf->servers;
1837 if (!acc && !(*realm)->parent && !srvconf->servers) {
1838 subrealm = adddynamicrealmserver(*realm, srvconf, id);
1840 pthread_mutex_lock(&subrealm->mutex);
1841 pthread_mutex_unlock(&(*realm)->mutex);
1844 server = ((struct clsrvconf *)subrealm->srvconfs->first->data)->servers;
1853 struct request *newrequest() {
1856 rq = malloc(sizeof(struct request));
1858 debug(DBG_ERR, "newrequest: malloc failed");
1861 memset(rq, 0, sizeof(struct request));
1863 gettimeofday(&rq->created, NULL);
1867 int addclientrq(struct request *rq) {
1871 r = rq->from->rqs[rq->rqid];
1873 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1874 gettimeofday(&now, NULL);
1875 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1877 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1878 sendreply(newrqref(r));
1880 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1886 rq->from->rqs[rq->rqid] = newrqref(rq);
1890 void rmclientrq(struct request *rq, uint8_t id) {
1893 r = rq->from->rqs[id];
1896 rq->from->rqs[id] = NULL;
1900 /* returns 0 if validation/authentication fails, else 1 */
1901 int radsrv(struct request *rq) {
1902 struct radmsg *msg = NULL;
1904 uint8_t *userascii = NULL;
1905 struct realm *realm = NULL;
1906 struct server *to = NULL;
1907 struct client *from = rq->from;
1910 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1915 debug(DBG_WARN, "radsrv: message validation failed, ignoring packet");
1922 memcpy(rq->rqauth, msg->auth, 16);
1924 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1925 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1926 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1930 if (!addclientrq(rq))
1933 if (msg->code == RAD_Status_Server) {
1934 respond(rq, RAD_Access_Accept, NULL);
1938 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1940 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1943 ttlres = checkttl(msg, options.ttlattrtype);
1945 debug(DBG_WARN, "radsrv: ignoring request from client %s (%s), ttl exceeded", from->conf->name, addr2string(from->addr));
1949 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1951 if (msg->code == RAD_Accounting_Request) {
1952 acclog(msg, from->conf->host);
1953 respond(rq, RAD_Accounting_Response, NULL);
1955 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1959 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1960 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1964 userascii = radattr2ascii(attr);
1967 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1969 /* will return with lock on the realm */
1970 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1972 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1977 if (realm->message && msg->code == RAD_Access_Request) {
1978 debug(DBG_INFO, "radsrv: sending reject to %s for %s", from->conf->host, userascii);
1979 respond(rq, RAD_Access_Reject, realm->message);
1980 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1981 acclog(msg, from->conf->host);
1982 respond(rq, RAD_Accounting_Response, NULL);
1987 if (options.loopprevention && !strcmp(from->conf->name, to->conf->name)) {
1988 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s (%s) to server %s, discarding",
1989 from->conf->name, addr2string(from->addr), to->conf->name);
1993 if (msg->code == RAD_Accounting_Request)
1994 memset(msg->auth, 0, 16);
1995 else if (!RAND_bytes(msg->auth, 16)) {
1996 debug(DBG_WARN, "radsrv: failed to generate random auth");
2001 printfchars(NULL, "auth", "%02x ", auth, 16);
2004 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
2006 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
2007 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
2011 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
2013 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
2014 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
2018 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
2021 if (ttlres == -1 && (options.addttl || to->conf->addttl))
2022 addttlattr(msg, options.ttlattrtype, to->conf->addttl ? to->conf->addttl : options.addttl);
2027 pthread_mutex_unlock(&realm->mutex);
2032 rmclientrq(rq, msg->id);
2037 pthread_mutex_unlock(&realm->mutex);
2043 void replyh(struct server *server, unsigned char *buf) {
2044 struct client *from;
2045 struct rqout *rqout;
2047 unsigned char *subattrs;
2048 uint8_t *username, *stationid, *replymsg;
2049 struct radmsg *msg = NULL;
2051 struct list_node *node;
2053 server->connectionok = 1;
2054 server->lostrqs = 0;
2056 rqout = server->requests + buf[1];
2057 pthread_mutex_lock(rqout->lock);
2058 if (!rqout->tries) {
2061 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
2065 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
2069 debug(DBG_WARN, "replyh: message validation failed, ignoring packet");
2072 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
2073 && msg->code != RAD_Accounting_Response) {
2074 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
2077 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
2079 gettimeofday(&server->lastrcv, NULL);
2081 if (rqout->rq->msg->code == RAD_Status_Server) {
2082 freerqoutdata(rqout);
2083 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2087 gettimeofday(&server->lastreply, NULL);
2088 from = rqout->rq->from;
2090 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
2091 debug(DBG_WARN, "replyh: rewritein failed");
2095 ttlres = checkttl(msg, options.ttlattrtype);
2097 debug(DBG_WARN, "replyh: ignoring reply from server %s, ttl exceeded", server->conf->host);
2102 for (node = list_first(msg->attrs); node; node = list_next(node)) {
2103 attr = (struct tlv *)node->data;
2104 if (attr->t != RAD_Attr_Vendor_Specific)
2108 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
2111 sublen = attr->l - 4;
2112 subattrs = attr->v + 4;
2113 if (!attrvalidate(subattrs, sublen) ||
2114 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2115 rqout->rq, server->conf->secret, from->conf->secret) ||
2116 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2117 rqout->rq, server->conf->secret, from->conf->secret))
2121 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2125 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
2126 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
2128 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
2129 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
2132 debug(DBG_INFO, "%s for user %s stationid %s from %s (%s)",
2133 radmsgtype2string(msg->code), username, stationid, server->conf->host, replymsg);
2136 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2137 radmsgtype2string(msg->code), username, stationid, server->conf->host);
2141 debug(DBG_INFO, "%s for user %s from %s (%s)",
2142 radmsgtype2string(msg->code), username, server->conf->host, replymsg);
2145 debug(DBG_INFO, "%s for user %s from %s",
2146 radmsgtype2string(msg->code), username, server->conf->host);
2152 msg->id = (char)rqout->rq->rqid;
2153 memcpy(msg->auth, rqout->rq->rqauth, 16);
2156 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2159 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
2160 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
2161 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2164 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
2167 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
2168 debug(DBG_WARN, "replyh: rewriteout failed");
2172 if (ttlres == -1 && (options.addttl || from->conf->addttl))
2173 addttlattr(msg, options.ttlattrtype, from->conf->addttl ? from->conf->addttl : options.addttl);
2175 debug(DBG_INFO, "replyh: passing reply to client %s (%s)", from->conf->name, addr2string(from->addr));
2176 radmsg_free(rqout->rq->msg);
2177 rqout->rq->msg = msg;
2178 sendreply(newrqref(rqout->rq));
2179 freerqoutdata(rqout);
2180 pthread_mutex_unlock(rqout->lock);
2185 pthread_mutex_unlock(rqout->lock);
2189 struct request *createstatsrvrq() {
2196 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
2199 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
2202 if (!radmsg_add(rq->msg, attr)) {
2213 /* code for removing state not finished */
2214 void *clientwr(void *arg) {
2215 struct server *server = (struct server *)arg;
2216 struct rqout *rqout = NULL;
2217 pthread_t clientrdth;
2218 int i, dynconffail = 0;
2221 struct timeval now, laststatsrv;
2222 struct timespec timeout;
2223 struct request *statsrvrq;
2224 struct clsrvconf *conf;
2226 conf = server->conf;
2228 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2233 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2234 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2238 memset(&timeout, 0, sizeof(struct timespec));
2240 if (conf->statusserver) {
2241 gettimeofday(&server->lastrcv, NULL);
2242 gettimeofday(&laststatsrv, NULL);
2245 if (conf->pdef->connecter) {
2246 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2248 server->connectionok = 1;
2249 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
2250 debug(DBG_ERR, "clientwr: pthread_create failed");
2254 server->connectionok = 1;
2257 pthread_mutex_lock(&server->newrq_mutex);
2258 if (!server->newrq) {
2259 gettimeofday(&now, NULL);
2260 /* random 0-7 seconds */
2261 RAND_bytes(&rnd, 1);
2263 if (conf->statusserver) {
2264 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2265 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
2267 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
2268 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
2270 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2271 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2274 if (timeout.tv_sec > now.tv_sec)
2275 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2277 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2280 if (server->newrq) {
2281 debug(DBG_DBG, "clientwr: got new request");
2286 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2288 pthread_mutex_unlock(&server->newrq_mutex);
2290 for (i = 0; i < MAX_REQUESTS; i++) {
2291 if (server->clientrdgone) {
2292 pthread_join(clientrdth, NULL);
2296 for (; i < MAX_REQUESTS; i++) {
2297 rqout = server->requests + i;
2299 pthread_mutex_lock(rqout->lock);
2302 pthread_mutex_unlock(rqout->lock);
2306 if (i == MAX_REQUESTS)
2309 gettimeofday(&now, NULL);
2310 if (now.tv_sec < rqout->expiry.tv_sec) {
2311 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2312 timeout.tv_sec = rqout->expiry.tv_sec;
2313 pthread_mutex_unlock(rqout->lock);
2317 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2318 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2319 if (conf->statusserver) {
2320 if (*rqout->rq->buf == RAD_Status_Server) {
2321 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2322 if (server->lostrqs < 255)
2326 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2327 if (server->lostrqs < 255)
2330 freerqoutdata(rqout);
2331 pthread_mutex_unlock(rqout->lock);
2335 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2336 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2337 timeout.tv_sec = rqout->expiry.tv_sec;
2339 conf->pdef->clientradput(server, rqout->rq->buf);
2340 pthread_mutex_unlock(rqout->lock);
2342 if (conf->statusserver && server->connectionok) {
2343 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2344 gettimeofday(&now, NULL);
2345 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
2347 statsrvrq = createstatsrvrq();
2349 statsrvrq->to = server;
2350 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2357 conf->servers = NULL;
2358 if (server->dynamiclookuparg) {
2359 removeserversubrealms(realms, conf);
2363 freeclsrvconf(conf);
2365 freeserver(server, 1);
2366 ERR_remove_state(0);
2370 void createlistener(uint8_t type, char *arg) {
2372 struct clsrvconf *listenres;
2373 struct addrinfo *res;
2374 int s = -1, on = 1, *sp = NULL;
2376 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2378 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2380 for (res = listenres->addrinfo; res; res = res->ai_next) {
2381 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2383 debug(DBG_WARN, "createlistener: socket failed");
2386 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2388 if (res->ai_family == AF_INET6)
2389 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2391 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2392 debug(DBG_WARN, "createlistener: bind failed");
2398 sp = malloc(sizeof(int));
2400 debugx(1, DBG_ERR, "malloc failed");
2402 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
2403 debugx(1, DBG_ERR, "pthread_create failed");
2407 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2409 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
2410 listenres->host ? listenres->host : "*", listenres->port);
2411 freeclsrvres(listenres);
2414 void createlisteners(uint8_t type, char **args) {
2418 for (i = 0; args[i]; i++)
2419 createlistener(type, args[i]);
2421 createlistener(type, NULL);
2425 void ssl_info_callback(const SSL *ssl, int where, int ret) {
2429 w = where & ~SSL_ST_MASK;
2431 if (w & SSL_ST_CONNECT)
2433 else if (w & SSL_ST_ACCEPT)
2438 if (where & SSL_CB_LOOP)
2439 debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
2440 else if (where & SSL_CB_ALERT) {
2441 s = (where & SSL_CB_READ) ? "read" : "write";
2442 debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
2444 else if (where & SSL_CB_EXIT) {
2446 debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
2448 debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
2458 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2459 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2460 for (i = 0; i < CRYPTO_num_locks(); i++) {
2461 ssl_lock_count[i] = 0;
2462 pthread_mutex_init(&ssl_locks[i], NULL);
2464 CRYPTO_set_id_callback(ssl_thread_id);
2465 CRYPTO_set_locking_callback(ssl_locking_callback);
2467 SSL_load_error_strings();
2470 while (!RAND_status()) {
2473 RAND_seed((unsigned char *)&t, sizeof(time_t));
2474 RAND_seed((unsigned char *)&pid, sizeof(pid));
2478 X509_VERIFY_PARAM *createverifyparams(char **poids) {
2479 X509_VERIFY_PARAM *pm;
2480 ASN1_OBJECT *pobject;
2483 pm = X509_VERIFY_PARAM_new();
2487 for (i = 0; poids[i]; i++) {
2488 pobject = OBJ_txt2obj(poids[i], 0);
2490 X509_VERIFY_PARAM_free(pm);
2493 X509_VERIFY_PARAM_add0_policy(pm, pobject);
2496 X509_VERIFY_PARAM_set_flags(pm, X509_V_FLAG_POLICY_CHECK | X509_V_FLAG_EXPLICIT_POLICY);
2500 int tlsaddcacrl(SSL_CTX *ctx, struct tls *conf) {
2501 STACK_OF(X509_NAME) *calist;
2503 unsigned long error;
2505 if (!SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2506 while ((error = ERR_get_error()))
2507 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2508 debug(DBG_ERR, "tlsaddcacrl: Error updating TLS context %s", conf->name);
2512 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2513 if (!conf->cacertfile || calist) {
2514 if (conf->cacertpath) {
2516 calist = sk_X509_NAME_new_null();
2517 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2518 sk_X509_NAME_free(calist);
2524 while ((error = ERR_get_error()))
2525 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2526 debug(DBG_ERR, "tlsaddcacrl: Error adding CA subjects in TLS context %s", conf->name);
2529 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2530 SSL_CTX_set_client_CA_list(ctx, calist);
2532 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2533 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2535 if (conf->crlcheck || conf->vpm) {
2536 x509_s = SSL_CTX_get_cert_store(ctx);
2538 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2540 X509_STORE_set1_param(x509_s, conf->vpm);
2543 debug(DBG_DBG, "tlsaddcacrl: updated TLS context %s", conf->name);
2547 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2548 SSL_CTX *ctx = NULL;
2549 unsigned long error;
2556 ctx = SSL_CTX_new(TLSv1_method());
2558 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2562 ctx = SSL_CTX_new(DTLSv1_method());
2564 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2566 SSL_CTX_set_read_ahead(ctx, 1);
2570 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2574 if (conf->certkeypwd) {
2575 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2576 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2578 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2579 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2580 !SSL_CTX_check_private_key(ctx)) {
2581 while ((error = ERR_get_error()))
2582 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2583 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2588 if (conf->policyoids) {
2590 conf->vpm = createverifyparams(conf->policyoids);
2592 debug(DBG_ERR, "tlsaddcacrl: Failed to add policyOIDs in TLS context %s", conf->name);
2599 if (!tlsaddcacrl(ctx, conf)) {
2601 X509_VERIFY_PARAM_free(conf->vpm);
2608 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
2612 struct tls *tlsgettls(char *alt1, char *alt2) {
2615 t = hash_read(tlsconfs, alt1, strlen(alt1));
2617 t = hash_read(tlsconfs, alt2, strlen(alt2));
2621 SSL_CTX *tlsgetctx(uint8_t type, struct tls *t) {
2626 gettimeofday(&now, NULL);
2630 if (t->tlsexpiry && t->tlsctx) {
2631 if (t->tlsexpiry < now.tv_sec) {
2632 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
2633 tlsaddcacrl(t->tlsctx, t);
2637 t->tlsctx = tlscreatectx(RAD_TLS, t);
2639 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
2643 if (t->dtlsexpiry && t->dtlsctx) {
2644 if (t->dtlsexpiry < now.tv_sec) {
2645 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
2646 tlsaddcacrl(t->dtlsctx, t);
2650 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2652 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
2659 struct list *addsrvconfs(char *value, char **names) {
2660 struct list *conflist;
2662 struct list_node *entry;
2663 struct clsrvconf *conf = NULL;
2665 if (!names || !*names)
2668 conflist = list_create();
2670 debug(DBG_ERR, "malloc failed");
2674 for (n = 0; names[n]; n++) {
2675 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2676 conf = (struct clsrvconf *)entry->data;
2677 if (!strcasecmp(names[n], conf->name))
2681 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2682 list_destroy(conflist);
2685 if (!list_push(conflist, conf)) {
2686 debug(DBG_ERR, "malloc failed");
2687 list_destroy(conflist);
2690 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2695 void freerealm(struct realm *realm) {
2698 debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2699 if (--realm->refcount)
2703 free(realm->message);
2704 regfree(&realm->regex);
2705 pthread_mutex_destroy(&realm->mutex);
2706 /* if refcount == 0, all subrealms gone */
2707 list_destroy(realm->subrealms);
2708 /* if refcount == 0, all srvconfs gone */
2709 list_destroy(realm->srvconfs);
2710 /* if refcount == 0, all accsrvconfs gone */
2711 list_destroy(realm->accsrvconfs);
2712 freerealm(realm->parent);
2716 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2718 struct realm *realm;
2719 char *s, *regex = NULL;
2721 if (*value == '/') {
2722 /* regexp, remove optional trailing / if present */
2723 if (value[strlen(value) - 1] == '/')
2724 value[strlen(value) - 1] = '\0';
2726 /* not a regexp, let us make it one */
2727 if (*value == '*' && !value[1])
2728 regex = stringcopy(".*", 0);
2730 for (n = 0, s = value; *s;)
2733 regex = malloc(strlen(value) + n + 3);
2736 for (n = 1, s = value; *s; s++) {
2746 debug(DBG_ERR, "malloc failed");
2750 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2753 realm = malloc(sizeof(struct realm));
2755 debug(DBG_ERR, "malloc failed");
2758 memset(realm, 0, sizeof(struct realm));
2760 if (pthread_mutex_init(&realm->mutex, NULL)) {
2761 debug(DBG_ERR, "mutex init failed");
2767 realm->name = stringcopy(value, 0);
2769 debug(DBG_ERR, "malloc failed");
2772 if (message && strlen(message) > 253) {
2773 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2776 realm->message = message;
2777 realm->accresp = accresp;
2779 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2780 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2784 if (servers && *servers) {
2785 realm->srvconfs = addsrvconfs(value, servers);
2786 if (!realm->srvconfs)
2790 if (accservers && *accservers) {
2791 realm->accsrvconfs = addsrvconfs(value, accservers);
2792 if (!realm->accsrvconfs)
2796 if (!list_push(realmlist, realm)) {
2797 debug(DBG_ERR, "malloc failed");
2798 pthread_mutex_destroy(&realm->mutex);
2802 debug(DBG_DBG, "addrealm: added realm %s", value);
2806 while (list_shift(realm->srvconfs));
2807 while (list_shift(realm->accsrvconfs));
2814 for (n = 0; servers[n]; n++)
2816 freegconfmstr(servers);
2820 for (n = 0; accservers[n]; n++)
2822 freegconfmstr(accservers);
2824 return newrealmref(realm);
2827 struct realm *adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2828 struct clsrvconf *srvconf;
2829 struct realm *newrealm = NULL;
2830 char *realmname, *s;
2833 if (!conf->dynamiclookupcommand)
2836 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2837 realmname = strrchr(id, '@');
2843 for (s = realmname; *s; s++)
2844 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2847 srvconf = malloc(sizeof(struct clsrvconf));
2849 debug(DBG_ERR, "malloc failed");
2853 if (!addserver(srvconf))
2856 if (!realm->subrealms)
2857 realm->subrealms = list_create();
2858 if (!realm->subrealms)
2860 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2863 newrealm->parent = newrealmref(realm);
2865 /* add server and accserver to newrealm */
2866 newrealm->srvconfs = list_create();
2867 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2868 debug(DBG_ERR, "malloc failed");
2871 newrealmref(newrealm);
2872 newrealm->accsrvconfs = list_create();
2873 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2874 debug(DBG_ERR, "malloc failed");
2875 list_shift(realm->srvconfs);
2876 freerealm(newrealm);
2879 newrealmref(newrealm);
2881 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2882 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2883 debug(DBG_ERR, "pthread_create failed");
2884 list_shift(realm->srvconfs);
2885 freerealm(newrealm);
2886 list_shift(realm->accsrvconfs);
2887 freerealm(newrealm);
2890 pthread_detach(clientth);
2895 list_removedata(realm->subrealms, newrealm);
2896 freerealm(newrealm);
2897 if (!list_first(realm->subrealms)) {
2898 list_destroy(realm->subrealms);
2899 realm->subrealms = NULL;
2902 freeserver(srvconf->servers, 1);
2904 debug(DBG_ERR, "failed to create dynamic server");
2908 int dynamicconfig(struct server *server) {
2909 int ok, fd[2], status;
2911 struct clsrvconf *conf = server->conf;
2912 struct gconffile *cf = NULL;
2914 /* for now we only learn hostname/address */
2915 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2918 debug(DBG_ERR, "dynamicconfig: pipe error");
2923 debug(DBG_ERR, "dynamicconfig: fork error");
2927 } else if (pid == 0) {
2930 if (fd[1] != STDOUT_FILENO) {
2931 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2932 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2935 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2936 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2940 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2941 ok = getgenericconfig(&cf, NULL,
2942 "Server", CONF_CBK, confserver_cb, (void *)conf,
2947 if (waitpid(pid, &status, 0) < 0) {
2948 debug(DBG_ERR, "dynamicconfig: wait error");
2953 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2961 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2965 int addmatchcertattr(struct clsrvconf *conf) {
2969 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2970 r = &conf->certcnregex;
2971 v = conf->matchcertattr + 4;
2972 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2973 r = &conf->certuriregex;
2974 v = conf->matchcertattr + 20;
2979 /* regexp, remove optional trailing / if present */
2980 if (v[strlen(v) - 1] == '/')
2981 v[strlen(v) - 1] = '\0';
2985 *r = malloc(sizeof(regex_t));
2987 debug(DBG_ERR, "malloc failed");
2990 if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2993 debug(DBG_ERR, "failed to compile regular expression %s", v);
2999 /* should accept both names and numeric values, only numeric right now */
3000 uint8_t attrname2val(char *attrname) {
3003 val = atoi(attrname);
3004 return val > 0 && val < 256 ? val : 0;
3007 /* should accept both names and numeric values, only numeric right now */
3008 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
3011 *vendor = atoi(attrname);
3012 s = strchr(attrname, ':');
3017 *type = atoi(s + 1);
3018 return *type >= 0 && *type < 256;
3021 /* should accept both names and numeric values, only numeric right now */
3022 struct tlv *extractattr(char *nameval) {
3027 s = strchr(nameval, ':');
3028 name = atoi(nameval);
3029 if (!s || name < 1 || name > 255)
3031 len = strlen(s + 1);
3034 a = malloc(sizeof(struct tlv));
3037 a->v = (uint8_t *)stringcopy(s + 1, 0);
3047 /* should accept both names and numeric values, only numeric right now */
3048 struct modattr *extractmodattr(char *nameval) {
3053 if (!strncasecmp(nameval, "User-Name:/", 11)) {
3057 s = strchr(nameval, ':');
3058 name = atoi(nameval);
3059 if (!s || name < 1 || name > 255 || s[1] != '/')
3063 /* regexp, remove optional trailing / if present */
3064 if (s[strlen(s) - 1] == '/')
3065 s[strlen(s) - 1] = '\0';
3073 m = malloc(sizeof(struct modattr));
3075 debug(DBG_ERR, "malloc failed");
3080 m->replacement = stringcopy(t, 0);
3081 if (!m->replacement) {
3083 debug(DBG_ERR, "malloc failed");
3087 m->regex = malloc(sizeof(regex_t));
3089 free(m->replacement);
3091 debug(DBG_ERR, "malloc failed");
3095 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
3097 free(m->replacement);
3099 debug(DBG_ERR, "failed to compile regular expression %s", s);
3106 struct rewrite *getrewrite(char *alt1, char *alt2) {
3109 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
3111 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
3116 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
3117 struct rewrite *rewrite = NULL;
3119 uint8_t *rma = NULL;
3120 uint32_t *p, *rmva = NULL;
3121 struct list *adda = NULL, *moda = NULL;
3126 for (n = 0; rmattrs[n]; n++);
3127 rma = calloc(n + 1, sizeof(uint8_t));
3129 debugx(1, DBG_ERR, "malloc failed");
3131 for (i = 0; i < n; i++)
3132 if (!(rma[i] = attrname2val(rmattrs[i])))
3133 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
3134 freegconfmstr(rmattrs);
3139 for (n = 0; rmvattrs[n]; n++);
3140 rmva = calloc(2 * n + 1, sizeof(uint32_t));
3142 debugx(1, DBG_ERR, "malloc failed");
3144 for (p = rmva, i = 0; i < n; i++, p += 2)
3145 if (!vattrname2val(rmvattrs[i], p, p + 1))
3146 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
3147 freegconfmstr(rmvattrs);
3152 adda = list_create();
3154 debugx(1, DBG_ERR, "malloc failed");
3155 for (i = 0; addattrs[i]; i++) {
3156 a = extractattr(addattrs[i]);
3158 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
3159 if (!list_push(adda, a))
3160 debugx(1, DBG_ERR, "malloc failed");
3162 freegconfmstr(addattrs);
3166 moda = list_create();
3168 debugx(1, DBG_ERR, "malloc failed");
3169 for (i = 0; modattrs[i]; i++) {
3170 m = extractmodattr(modattrs[i]);
3172 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
3173 if (!list_push(moda, m))
3174 debugx(1, DBG_ERR, "malloc failed");
3176 freegconfmstr(modattrs);
3179 if (rma || rmva || adda || moda) {
3180 rewrite = malloc(sizeof(struct rewrite));
3182 debugx(1, DBG_ERR, "malloc failed");
3183 rewrite->removeattrs = rma;
3184 rewrite->removevendorattrs = rmva;
3185 rewrite->addattrs = adda;
3186 rewrite->modattrs = moda;
3189 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
3190 debugx(1, DBG_ERR, "malloc failed");
3191 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3194 int setttlattr(struct options *opts, char *defaultattr) {
3195 char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
3197 if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
3198 (opts->ttlattrtype[1] != -1 || opts->ttlattrtype[0] < 256))
3200 debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
3204 void freeclsrvconf(struct clsrvconf *conf) {
3210 free(conf->matchcertattr);
3211 if (conf->certcnregex)
3212 regfree(conf->certcnregex);
3213 if (conf->certuriregex)
3214 regfree(conf->certuriregex);
3215 free(conf->confrewritein);
3216 free(conf->confrewriteout);
3217 if (conf->rewriteusername) {
3218 if (conf->rewriteusername->regex)
3219 regfree(conf->rewriteusername->regex);
3220 free(conf->rewriteusername->replacement);
3221 free(conf->rewriteusername);
3223 free(conf->dynamiclookupcommand);
3224 free(conf->rewritein);
3225 free(conf->rewriteout);
3227 freeaddrinfo(conf->addrinfo);
3229 pthread_mutex_destroy(conf->lock);
3232 /* not touching ssl_ctx, clients and servers */
3236 int mergeconfstring(char **dst, char **src) {
3245 t = stringcopy(*dst, 0);
3247 debug(DBG_ERR, "malloc failed");
3255 /* assumes dst is a shallow copy */
3256 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3257 if (!mergeconfstring(&dst->name, &src->name) ||
3258 !mergeconfstring(&dst->host, &src->host) ||
3259 !mergeconfstring(&dst->port, &src->port) ||
3260 !mergeconfstring(&dst->secret, &src->secret) ||
3261 !mergeconfstring(&dst->tls, &src->tls) ||
3262 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3263 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
3264 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
3265 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3268 dst->pdef = src->pdef;
3269 dst->statusserver = src->statusserver;
3270 dst->certnamecheck = src->certnamecheck;
3271 if (src->retryinterval != 255)
3272 dst->retryinterval = src->retryinterval;
3273 if (src->retrycount != 255)
3274 dst->retrycount = src->retrycount;
3278 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3279 struct clsrvconf *conf;
3280 char *conftype = NULL, *rewriteinalias = NULL;
3281 long int dupinterval = LONG_MIN, addttl = LONG_MIN;
3283 debug(DBG_DBG, "confclient_cb called for %s", block);
3285 conf = malloc(sizeof(struct clsrvconf));
3287 debugx(1, DBG_ERR, "malloc failed");
3288 memset(conf, 0, sizeof(struct clsrvconf));
3289 conf->certnamecheck = 1;
3291 if (!getgenericconfig(cf, block,
3292 "type", CONF_STR, &conftype,
3293 "host", CONF_STR, &conf->host,
3294 "secret", CONF_STR, &conf->secret,
3295 "tls", CONF_STR, &conf->tls,
3296 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3297 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3298 "DuplicateInterval", CONF_LINT, &dupinterval,
3299 "addTTL", CONF_LINT, &addttl,
3300 "rewrite", CONF_STR, &rewriteinalias,
3301 "rewriteIn", CONF_STR, &conf->confrewritein,
3302 "rewriteOut", CONF_STR, &conf->confrewriteout,
3303 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
3306 debugx(1, DBG_ERR, "configuration error");
3308 conf->name = stringcopy(val, 0);
3310 conf->host = stringcopy(val, 0);
3311 if (!conf->name || !conf->host)
3312 debugx(1, DBG_ERR, "malloc failed");
3315 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3316 conf->type = protoname2int(conftype);
3317 conf->pdef = &protodefs[conf->type];
3318 if (!conf->pdef->name)
3319 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3322 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3323 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
3325 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3326 if (conf->matchcertattr && !addmatchcertattr(conf))
3327 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3330 if (dupinterval != LONG_MIN) {
3331 if (dupinterval < 0 || dupinterval > 255)
3332 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
3333 conf->dupinterval = (uint8_t)dupinterval;
3335 conf->dupinterval = conf->pdef->duplicateintervaldefault;
3337 if (addttl != LONG_MIN) {
3338 if (addttl < 1 || addttl > 255)
3339 debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
3340 conf->addttl = (uint8_t)addttl;
3343 if (!conf->confrewritein)
3344 conf->confrewritein = rewriteinalias;
3346 free(rewriteinalias);
3347 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
3348 if (conf->confrewriteout)
3349 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3351 if (conf->confrewriteusername) {
3352 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
3353 if (!conf->rewriteusername)
3354 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3357 if (!resolvepeer(conf, 0))
3358 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3360 if (!conf->secret) {
3361 if (!conf->pdef->secretdefault)
3362 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3363 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3365 debugx(1, DBG_ERR, "malloc failed");
3368 conf->lock = malloc(sizeof(pthread_mutex_t));
3370 debugx(1, DBG_ERR, "malloc failed");
3372 pthread_mutex_init(conf->lock, NULL);
3373 if (!list_push(clconfs, conf))
3374 debugx(1, DBG_ERR, "malloc failed");
3378 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3379 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3380 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
3381 if (!conf->tlsconf) {
3382 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3385 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3386 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3392 conf->port = stringcopy(conf->pdef->portdefault, 0);
3394 debug(DBG_ERR, "malloc failed");
3399 if (conf->retryinterval == 255)
3400 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3401 if (conf->retrycount == 255)
3402 conf->retrycount = protodefs[conf->type].retrycountdefault;
3404 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
3405 if (conf->confrewriteout)
3406 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3408 if (!conf->secret) {
3409 if (!conf->pdef->secretdefault) {
3410 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3413 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3414 if (!conf->secret) {
3415 debug(DBG_ERR, "malloc failed");
3420 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3421 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3427 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3428 struct clsrvconf *conf, *resconf;
3429 char *conftype = NULL, *rewriteinalias = NULL;
3430 long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
3432 debug(DBG_DBG, "confserver_cb called for %s", block);
3434 conf = malloc(sizeof(struct clsrvconf));
3436 debug(DBG_ERR, "malloc failed");
3439 memset(conf, 0, sizeof(struct clsrvconf));
3440 resconf = (struct clsrvconf *)arg;
3442 conf->statusserver = resconf->statusserver;
3443 conf->certnamecheck = resconf->certnamecheck;
3445 conf->certnamecheck = 1;
3447 if (!getgenericconfig(cf, block,
3448 "type", CONF_STR, &conftype,
3449 "host", CONF_STR, &conf->host,
3450 "port", CONF_STR, &conf->port,
3451 "secret", CONF_STR, &conf->secret,
3452 "tls", CONF_STR, &conf->tls,
3453 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3454 "addTTL", CONF_LINT, &addttl,
3455 "rewrite", CONF_STR, &rewriteinalias,
3456 "rewriteIn", CONF_STR, &conf->confrewritein,
3457 "rewriteOut", CONF_STR, &conf->confrewriteout,
3458 "StatusServer", CONF_BLN, &conf->statusserver,
3459 "RetryInterval", CONF_LINT, &retryinterval,
3460 "RetryCount", CONF_LINT, &retrycount,
3461 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3462 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3465 debug(DBG_ERR, "configuration error");
3469 conf->name = stringcopy(val, 0);
3471 debug(DBG_ERR, "malloc failed");
3475 conf->host = stringcopy(val, 0);
3477 debug(DBG_ERR, "malloc failed");
3483 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3484 conf->type = protoname2int(conftype);
3485 conf->pdef = &protodefs[conf->type];
3486 if (!conf->pdef->name) {
3487 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3493 if (!conf->confrewritein)
3494 conf->confrewritein = rewriteinalias;
3496 free(rewriteinalias);
3497 rewriteinalias = NULL;
3499 if (retryinterval != LONG_MIN) {
3500 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3501 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3504 conf->retryinterval = (uint8_t)retryinterval;
3506 conf->retryinterval = 255;
3508 if (retrycount != LONG_MIN) {
3509 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3510 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3513 conf->retrycount = (uint8_t)retrycount;
3515 conf->retrycount = 255;
3517 if (addttl != LONG_MIN) {
3518 if (addttl < 1 || addttl > 255) {
3519 debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
3522 conf->addttl = (uint8_t)addttl;
3526 if (!mergesrvconf(resconf, conf))
3530 if (conf->dynamiclookupcommand) {
3531 free(conf->dynamiclookupcommand);
3532 conf->dynamiclookupcommand = NULL;
3536 if (resconf || !conf->dynamiclookupcommand) {
3537 if (!compileserverconfig(conf, block))
3544 if (!list_push(srvconfs, conf)) {
3545 debug(DBG_ERR, "malloc failed");
3552 free(rewriteinalias);
3553 freeclsrvconf(conf);
3557 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3558 char **servers = NULL, **accservers = NULL, *msg = NULL;
3559 uint8_t accresp = 0;
3561 debug(DBG_DBG, "confrealm_cb called for %s", block);
3563 if (!getgenericconfig(cf, block,
3564 "server", CONF_MSTR, &servers,
3565 "accountingServer", CONF_MSTR, &accservers,
3566 "ReplyMessage", CONF_STR, &msg,
3567 "AccountingResponse", CONF_BLN, &accresp,
3570 debugx(1, DBG_ERR, "configuration error");
3572 addrealm(realms, val, servers, accservers, msg, accresp);
3576 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3578 long int expiry = LONG_MIN;
3580 debug(DBG_DBG, "conftls_cb called for %s", block);
3582 conf = malloc(sizeof(struct tls));
3584 debug(DBG_ERR, "conftls_cb: malloc failed");
3587 memset(conf, 0, sizeof(struct tls));
3589 if (!getgenericconfig(cf, block,
3590 "CACertificateFile", CONF_STR, &conf->cacertfile,
3591 "CACertificatePath", CONF_STR, &conf->cacertpath,
3592 "CertificateFile", CONF_STR, &conf->certfile,
3593 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3594 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3595 "CacheExpiry", CONF_LINT, &expiry,
3596 "CRLCheck", CONF_BLN, &conf->crlcheck,
3597 "PolicyOID", CONF_MSTR, &conf->policyoids,
3600 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3603 if (!conf->certfile || !conf->certkeyfile) {
3604 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3607 if (!conf->cacertfile && !conf->cacertpath) {
3608 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3611 if (expiry != LONG_MIN) {
3613 debug(DBG_ERR, "error in block %s, value of option CacheExpiry is %ld, may not be negative", val, expiry);
3616 conf->cacheexpiry = expiry;
3619 conf->name = stringcopy(val, 0);
3621 debug(DBG_ERR, "conftls_cb: malloc failed");
3625 if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
3626 debug(DBG_ERR, "conftls_cb: malloc failed");
3629 if (!tlsgetctx(RAD_TLS, conf))
3630 debug(DBG_ERR, "conftls_cb: error creating ctx for TLS block %s", val);
3631 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3635 free(conf->cacertfile);
3636 free(conf->cacertpath);
3637 free(conf->certfile);
3638 free(conf->certkeyfile);
3639 free(conf->certkeypwd);
3640 freegconfmstr(conf->policyoids);
3645 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3646 char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3648 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3650 if (!getgenericconfig(cf, block,
3651 "removeAttribute", CONF_MSTR, &rmattrs,
3652 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3653 "addAttribute", CONF_MSTR, &addattrs,
3654 "modifyAttribute", CONF_MSTR, &modattrs,
3657 debugx(1, DBG_ERR, "configuration error");
3658 addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3662 void getmainconfig(const char *configfile) {
3663 long int addttl = LONG_MIN, loglevel = LONG_MIN;
3664 struct gconffile *cfs;
3666 cfs = openconfigfile(configfile);
3667 memset(&options, 0, sizeof(options));
3669 clconfs = list_create();
3671 debugx(1, DBG_ERR, "malloc failed");
3673 srvconfs = list_create();
3675 debugx(1, DBG_ERR, "malloc failed");
3677 realms = list_create();
3679 debugx(1, DBG_ERR, "malloc failed");
3681 tlsconfs = hash_create();
3683 debugx(1, DBG_ERR, "malloc failed");
3685 rewriteconfs = hash_create();
3687 debugx(1, DBG_ERR, "malloc failed");
3689 if (!getgenericconfig(&cfs, NULL,
3690 "ListenUDP", CONF_MSTR, &options.listenargs[RAD_UDP],
3691 "ListenTCP", CONF_MSTR, &options.listenargs[RAD_TCP],
3692 "ListenTLS", CONF_MSTR, &options.listenargs[RAD_TLS],
3693 "ListenDTLS", CONF_MSTR, &options.listenargs[RAD_DTLS],
3694 "SourceUDP", CONF_STR, &options.sourcearg[RAD_UDP],
3695 "SourceTCP", CONF_STR, &options.sourcearg[RAD_TCP],
3696 "SourceTLS", CONF_STR, &options.sourcearg[RAD_TLS],
3697 "SourceDTLS", CONF_STR, &options.sourcearg[RAD_DTLS],
3698 "TTLAttribute", CONF_STR, &options.ttlattr,
3699 "addTTL", CONF_LINT, &addttl,
3700 "LogLevel", CONF_LINT, &loglevel,
3701 "LogDestination", CONF_STR, &options.logdestination,
3702 "LoopPrevention", CONF_BLN, &options.loopprevention,
3703 "Client", CONF_CBK, confclient_cb, NULL,
3704 "Server", CONF_CBK, confserver_cb, NULL,
3705 "Realm", CONF_CBK, confrealm_cb, NULL,
3706 "TLS", CONF_CBK, conftls_cb, NULL,
3707 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3710 debugx(1, DBG_ERR, "configuration error");
3712 if (loglevel != LONG_MIN) {
3713 if (loglevel < 1 || loglevel > 4)
3714 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3715 options.loglevel = (uint8_t)loglevel;
3717 if (addttl != LONG_MIN) {
3718 if (addttl < 1 || addttl > 255)
3719 debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3720 options.addttl = (uint8_t)addttl;
3722 if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3723 debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3726 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3729 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3732 *configfile = optarg;
3735 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3736 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3737 *loglevel = *optarg - '0';
3746 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3751 if (!(argc - optind))
3755 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3759 int daemon(int a, int b) {
3767 for (i = 0; i < 3; i++) {
3769 open("/dev/null", O_RDWR);
3775 void *sighandler(void *arg) {
3780 sigemptyset(&sigset);
3781 sigaddset(&sigset, SIGPIPE);
3782 sigwait(&sigset, &sig);
3783 /* only get SIGPIPE right now, so could simplify below code */
3786 /* completely ignoring this */
3789 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3792 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3797 int main(int argc, char **argv) {
3800 struct list_node *entry;
3801 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3802 char *configfile = NULL;
3803 struct clsrvconf *srvconf;
3806 debug_init("radsecproxy");
3807 debug_set_level(DEBUG_LEVEL);
3809 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3811 debug_set_level(loglevel);
3812 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3814 options.loglevel = loglevel;
3815 else if (options.loglevel)
3816 debug_set_level(options.loglevel);
3818 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3819 free(options.logdestination);
3821 if (!list_first(clconfs))
3822 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3823 if (!list_first(realms))
3824 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3827 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3829 if (!foreground && (daemon(0, 0) < 0))
3830 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3832 debug_timestamp_on();
3833 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3835 sigemptyset(&sigset);
3836 /* exit on all but SIGPIPE, ignore more? */
3837 sigaddset(&sigset, SIGPIPE);
3838 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3839 pthread_create(&sigth, NULL, sighandler, NULL);
3841 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3842 srvconf = (struct clsrvconf *)entry->data;
3843 if (srvconf->dynamiclookupcommand)
3845 if (!addserver(srvconf))
3846 debugx(1, DBG_ERR, "failed to add server");
3847 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3848 (void *)(srvconf->servers)))
3849 debugx(1, DBG_ERR, "pthread_create failed");
3852 for (i = 0; protodefs[i].name; i++) {
3853 if (protodefs[i].initextra)
3854 protodefs[i].initextra();
3855 if (find_clconf_type(i, NULL))
3856 createlisteners(i, options.listenargs[i]);
3859 /* just hang around doing nothing, anything to do here? */