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 */
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 = 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 };
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) {
949 memset(&rqout->expiry, 0, sizeof(struct timeval));
952 void sendrq(struct request *rq) {
956 removeclientrqs_sendrq_freeserver_lock(1);
961 start = to->conf->statusserver ? 1 : 0;
962 pthread_mutex_lock(&to->newrq_mutex);
963 if (start && rq->msg->code == RAD_Status_Server) {
964 pthread_mutex_lock(to->requests[0].lock);
965 if (to->requests[0].rq) {
966 pthread_mutex_unlock(to->requests[0].lock);
967 debug(DBG_WARN, "sendrq: status server already in queue, dropping request");
974 /* might simplify if only try nextid, might be ok */
975 for (i = to->nextid; i < MAX_REQUESTS; i++) {
976 if (!to->requests[i].rq) {
977 pthread_mutex_lock(to->requests[i].lock);
978 if (!to->requests[i].rq)
980 pthread_mutex_unlock(to->requests[i].lock);
983 if (i == MAX_REQUESTS) {
984 for (i = start; i < to->nextid; i++) {
985 if (!to->requests[i].rq) {
986 pthread_mutex_lock(to->requests[i].lock);
987 if (!to->requests[i].rq)
989 pthread_mutex_unlock(to->requests[i].lock);
992 if (i == to->nextid) {
993 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
998 rq->newid = (uint8_t)i;
999 rq->msg->id = (uint8_t)i;
1000 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
1002 pthread_mutex_unlock(to->requests[i].lock);
1003 debug(DBG_ERR, "sendrq: radmsg2buf failed");
1007 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1008 to->requests[i].rq = rq;
1009 pthread_mutex_unlock(to->requests[i].lock);
1010 if (i >= start) /* i is not reserved for statusserver */
1015 debug(DBG_DBG, "sendrq: signalling client writer");
1016 pthread_cond_signal(&to->newrq_cond);
1019 pthread_mutex_unlock(&to->newrq_mutex);
1020 removeclientrqs_sendrq_freeserver_lock(0);
1025 rmclientrq(rq, rq->msg->id);
1027 pthread_mutex_unlock(&to->newrq_mutex);
1028 removeclientrqs_sendrq_freeserver_lock(0);
1031 void sendreply(struct request *rq) {
1033 struct client *to = rq->from;
1036 rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
1037 radmsg_free(rq->msg);
1039 if (!rq->replybuf) {
1041 debug(DBG_ERR, "sendreply: radmsg2buf failed");
1045 pthread_mutex_lock(&to->replyq->mutex);
1046 first = list_first(to->replyq->entries) == NULL;
1048 if (!list_push(to->replyq->entries, rq)) {
1049 pthread_mutex_unlock(&to->replyq->mutex);
1051 debug(DBG_ERR, "sendreply: malloc failed");
1056 debug(DBG_DBG, "signalling server writer");
1057 pthread_cond_signal(&to->replyq->cond);
1059 pthread_mutex_unlock(&to->replyq->mutex);
1062 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1063 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1064 static unsigned char first = 1;
1065 static EVP_MD_CTX mdctx;
1066 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1067 unsigned int md_len;
1068 uint8_t i, offset = 0, out[128];
1070 pthread_mutex_lock(&lock);
1072 EVP_MD_CTX_init(&mdctx);
1078 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1079 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1080 !EVP_DigestUpdate(&mdctx, input, 16) ||
1081 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1083 pthread_mutex_unlock(&lock);
1086 for (i = 0; i < 16; i++)
1087 out[offset + i] = hash[i] ^ in[offset + i];
1088 input = out + offset - 16;
1093 memcpy(in, out, len);
1094 pthread_mutex_unlock(&lock);
1098 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1099 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1100 static unsigned char first = 1;
1101 static EVP_MD_CTX mdctx;
1102 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1103 unsigned int md_len;
1104 uint8_t i, offset = 0, out[128];
1106 pthread_mutex_lock(&lock);
1108 EVP_MD_CTX_init(&mdctx);
1114 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1115 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1116 !EVP_DigestUpdate(&mdctx, input, 16) ||
1117 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1119 pthread_mutex_unlock(&lock);
1122 for (i = 0; i < 16; i++)
1123 out[offset + i] = hash[i] ^ in[offset + i];
1124 input = in + offset;
1129 memcpy(in, out, len);
1130 pthread_mutex_unlock(&lock);
1134 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1135 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1136 static unsigned char first = 1;
1137 static EVP_MD_CTX mdctx;
1138 unsigned char hash[EVP_MAX_MD_SIZE];
1139 unsigned int md_len;
1142 pthread_mutex_lock(&lock);
1144 EVP_MD_CTX_init(&mdctx);
1149 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1150 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1151 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1154 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1155 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1156 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1157 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1158 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1159 pthread_mutex_unlock(&lock);
1164 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1167 for (i = 0; i < 16; i++)
1170 for (offset = 16; offset < len; offset += 16) {
1172 printf("text + offset - 16 c(%d): ", offset / 16);
1173 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1175 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1176 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1177 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1178 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1180 pthread_mutex_unlock(&lock);
1184 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1187 for (i = 0; i < 16; i++)
1188 text[offset + i] ^= hash[i];
1192 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1195 pthread_mutex_unlock(&lock);
1199 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1200 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1201 static unsigned char first = 1;
1202 static EVP_MD_CTX mdctx;
1203 unsigned char hash[EVP_MAX_MD_SIZE];
1204 unsigned int md_len;
1208 pthread_mutex_lock(&lock);
1210 EVP_MD_CTX_init(&mdctx);
1215 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1216 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1217 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1220 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1221 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1222 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1223 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1224 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1225 pthread_mutex_unlock(&lock);
1230 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1233 for (i = 0; i < 16; i++)
1234 plain[i] = text[i] ^ hash[i];
1236 for (offset = 16; offset < len; offset += 16) {
1238 printf("text + offset - 16 c(%d): ", offset / 16);
1239 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1241 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1242 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1243 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1244 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1246 pthread_mutex_unlock(&lock);
1250 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1253 for (i = 0; i < 16; i++)
1254 plain[offset + i] = text[offset + i] ^ hash[i];
1257 memcpy(text, plain, len);
1259 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1262 pthread_mutex_unlock(&lock);
1266 struct realm *newrealmref(struct realm *r) {
1272 /* returns with lock on realm */
1273 struct realm *id2realm(struct list *realmlist, char *id) {
1274 struct list_node *entry;
1275 struct realm *realm, *subrealm;
1277 /* need to do locking for subrealms and check subrealm timers */
1278 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1279 realm = (struct realm *)entry->data;
1280 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1281 pthread_mutex_lock(&realm->mutex);
1282 if (realm->subrealms) {
1283 subrealm = id2realm(realm->subrealms, id);
1285 pthread_mutex_unlock(&realm->mutex);
1289 return newrealmref(realm);
1295 /* helper function, only used by removeserversubrealms() */
1296 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1297 struct list_node *entry, *entry2;
1298 struct realm *realm;
1300 for (entry = list_first(realmlist); entry;) {
1301 realm = newrealmref((struct realm *)entry->data);
1302 pthread_mutex_lock(&realm->mutex);
1303 entry = list_next(entry);
1305 if (realm->srvconfs) {
1306 for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
1307 if (entry2->data == srv)
1309 list_removedata(realm->srvconfs, srv);
1310 if (!list_first(realm->srvconfs)) {
1311 list_destroy(realm->srvconfs);
1312 realm->srvconfs = NULL;
1315 if (realm->accsrvconfs) {
1316 for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
1317 if (entry2->data == srv)
1319 list_removedata(realm->accsrvconfs, srv);
1320 if (!list_first(realm->accsrvconfs)) {
1321 list_destroy(realm->accsrvconfs);
1322 realm->accsrvconfs = NULL;
1326 /* remove subrealm if no servers */
1327 if (!realm->srvconfs && !realm->accsrvconfs)
1328 list_removedata(realmlist, realm);
1330 pthread_mutex_unlock(&realm->mutex);
1335 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1336 struct list_node *entry;
1337 struct realm *realm;
1339 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1340 realm = (struct realm *)entry->data;
1341 pthread_mutex_lock(&realm->mutex);
1342 if (realm->subrealms) {
1343 _internal_removeserversubrealms(realm->subrealms, srv);
1344 if (!list_first(realm->subrealms)) {
1345 list_destroy(realm->subrealms);
1346 realm->subrealms = NULL;
1349 pthread_mutex_unlock(&realm->mutex);
1353 int attrvalidate(unsigned char *attrs, int length) {
1354 while (length > 1) {
1355 if (ATTRLEN(attrs) < 2) {
1356 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1359 length -= ATTRLEN(attrs);
1361 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1364 attrs += ATTRLEN(attrs);
1367 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1371 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1372 if (len < 16 || len > 128 || len % 16) {
1373 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1377 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1378 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1382 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1384 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1385 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1391 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1394 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1395 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1398 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
1399 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1405 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1406 char *oldsecret, char *newsecret) {
1407 unsigned char *attr;
1409 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1410 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1411 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
1417 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1421 for (; attrs[0]; attrs += 2)
1422 if (attrs[0] == vendor && attrs[1] == subattr)
1427 /* returns 1 if entire element is to be removed, else 0 */
1428 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
1429 uint8_t alen, sublen;
1433 if (!removevendorattrs)
1436 memcpy(&vendor, attr->v, 4);
1437 vendor = ntohl(vendor);
1438 while (*removevendorattrs && *removevendorattrs != vendor)
1439 removevendorattrs += 2;
1440 if (!*removevendorattrs)
1443 if (findvendorsubattr(removevendorattrs, vendor, -1))
1444 return 1; /* remove entire vendor attribute */
1446 sublen = attr->l - 4;
1447 subattrs = attr->v + 4;
1449 if (!attrvalidate(subattrs, sublen)) {
1450 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1454 while (sublen > 1) {
1455 alen = ATTRLEN(subattrs);
1457 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1458 memmove(subattrs, subattrs + alen, sublen);
1466 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
1467 struct list_node *n, *p;
1471 n = list_first(msg->attrs);
1473 attr = (struct tlv *)n->data;
1474 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
1475 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
1476 list_removedata(msg->attrs, attr);
1478 n = p ? list_next(p) : list_first(msg->attrs);
1485 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
1486 struct list_node *n;
1489 for (n = list_first(addattrs); n; n = list_next(n)) {
1490 a = copytlv((struct tlv *)n->data);
1493 if (!radmsg_add(msg, a)) {
1501 int resizeattr(struct tlv *attr, uint8_t newlen) {
1504 if (newlen != attr->l) {
1505 newv = realloc(attr->v, newlen);
1514 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1515 size_t nmatch = 10, reslen = 0, start = 0;
1516 regmatch_t pmatch[10], *pfield;
1520 in = stringcopy((char *)attr->v, attr->l);
1524 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1529 out = modattr->replacement;
1531 for (i = start; out[i]; i++) {
1532 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1533 pfield = &pmatch[out[i + 1] - '0'];
1534 if (pfield->rm_so >= 0) {
1535 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1541 reslen += i - start;
1543 debug(DBG_WARN, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1548 if (!resizeattr(attr, reslen)) {
1555 for (i = start; out[i]; i++) {
1556 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1557 pfield = &pmatch[out[i + 1] - '0'];
1558 if (pfield->rm_so >= 0) {
1559 memcpy(attr->v + reslen, out + start, i - start);
1560 reslen += i - start;
1561 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1562 reslen += pfield->rm_eo - pfield->rm_so;
1569 memcpy(attr->v + reslen, out + start, i - start);
1573 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1574 struct list_node *n, *m;
1576 for (n = list_first(msg->attrs); n; n = list_next(n))
1577 for (m = list_first(modattrs); m; m = list_next(m))
1578 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1579 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1584 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1587 if (rewrite->removeattrs || rewrite->removevendorattrs)
1588 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1589 if (rewrite->addattrs && !dorewriteadd(msg, rewrite->addattrs))
1591 if (rewrite->modattrs && !dorewritemod(msg, rewrite->modattrs))
1596 int rewriteusername(struct request *rq, struct tlv *attr) {
1597 char *orig = (char *)tlv2str(attr);
1598 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1602 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1603 rq->origusername = (char *)orig;
1609 int addvendorattr(struct radmsg *msg, uint32_t vendor, struct tlv *attr) {
1616 vendor = htonl(vendor);
1617 memcpy(v, &vendor, 4);
1618 tlv2buf(v + 4, attr);
1620 vattr = maketlv(RAD_Attr_Vendor_Specific, l, v);
1621 if (vattr && radmsg_add(msg, vattr))
1628 void addttlattr(struct radmsg *msg, uint32_t *attrtype, uint8_t addttl) {
1635 if (attrtype[1] == -1) { /* not vendor */
1636 attr = maketlv(attrtype[0], 4, ttl);
1637 if (attr && !radmsg_add(msg, attr))
1640 attr = maketlv(attrtype[1], 4, ttl);
1642 addvendorattr(msg, attrtype[0], attr);
1648 int decttl(uint8_t l, uint8_t *v) {
1655 while (i >= 0 && !v[i])
1659 for (i--; i >= 0 && !v[i]; i--);
1668 int dottl(struct radmsg *msg, uint32_t *attrtype, uint8_t addttl) {
1669 uint8_t alen, *subattrs;
1671 struct list_node *node;
1675 if (attrtype[1] == -1) { /* not vendor */
1676 attr = radmsg_gettype(msg, attrtype[0]);
1678 return decttl(attr->l, attr->v);
1680 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1681 attr = (struct tlv *)node->data;
1682 if (attr->t != RAD_Attr_Vendor_Specific || attr->l <= 4)
1684 memcpy(&vendor, attr->v, 4);
1685 if (ntohl(vendor) != attrtype[0])
1687 sublen = attr->l - 4;
1688 subattrs = attr->v + 4;
1689 if (!attrvalidate(subattrs, sublen))
1691 while (sublen > 1) {
1692 if (ATTRTYPE(subattrs) == attrtype[1])
1693 return decttl(ATTRVALLEN(subattrs), ATTRVAL(subattrs));
1694 alen = ATTRLEN(subattrs);
1700 addttlattr(msg, attrtype, addttl);
1704 const char *radmsgtype2string(uint8_t code) {
1705 static const char *rad_msg_names[] = {
1706 "", "Access-Request", "Access-Accept", "Access-Reject",
1707 "Accounting-Request", "Accounting-Response", "", "",
1708 "", "", "", "Access-Challenge",
1709 "Status-Server", "Status-Client"
1711 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1714 void char2hex(char *h, unsigned char c) {
1715 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1716 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1717 h[0] = hexdigits[c / 16];
1718 h[1] = hexdigits[c % 16];
1722 uint8_t *radattr2ascii(struct tlv *attr) {
1730 for (i = 0; i < attr->l; i++)
1731 if (attr->v[i] < 32 || attr->v[i] > 126)
1734 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1741 for (i = 0; i < attr->l; i++)
1742 if (attr->v[i] < 32 || attr->v[i] > 126) {
1744 char2hex((char *)d, attr->v[i]);
1752 void acclog(struct radmsg *msg, char *host) {
1756 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1758 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1761 username = radattr2ascii(attr);
1763 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1768 void respond(struct request *rq, uint8_t code, char *message) {
1772 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1774 debug(DBG_ERR, "respond: malloc failed");
1777 if (message && *message) {
1778 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1779 if (!attr || !radmsg_add(msg, attr)) {
1782 debug(DBG_ERR, "respond: malloc failed");
1787 radmsg_free(rq->msg);
1789 debug(DBG_DBG, "respond: sending %s to %s", radmsgtype2string(msg->code), rq->from->conf->host);
1790 sendreply(newrqref(rq));
1793 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1794 struct list_node *entry;
1795 struct clsrvconf *server, *best = NULL, *first = NULL;
1797 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1798 server = (struct clsrvconf *)entry->data;
1799 if (!server->servers)
1803 if (!server->servers->connectionok)
1805 if (!server->servers->lostrqs)
1811 if (server->servers->lostrqs < best->servers->lostrqs)
1814 return best ? best : first;
1817 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1818 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1819 struct clsrvconf *srvconf;
1820 struct realm *subrealm;
1821 struct server *server = NULL;
1822 char *id = (char *)tlv2str(username);
1826 /* returns with lock on realm */
1827 *realm = id2realm(realms, id);
1830 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1831 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1834 server = srvconf->servers;
1835 if (!acc && !(*realm)->parent && !srvconf->servers) {
1836 subrealm = adddynamicrealmserver(*realm, srvconf, id);
1838 pthread_mutex_lock(&subrealm->mutex);
1839 pthread_mutex_unlock(&(*realm)->mutex);
1842 server = ((struct clsrvconf *)subrealm->srvconfs->first->data)->servers;
1851 struct request *newrequest() {
1854 rq = malloc(sizeof(struct request));
1856 debug(DBG_ERR, "newrequest: malloc failed");
1859 memset(rq, 0, sizeof(struct request));
1861 gettimeofday(&rq->created, NULL);
1865 int addclientrq(struct request *rq) {
1869 r = rq->from->rqs[rq->rqid];
1871 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1872 gettimeofday(&now, NULL);
1873 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1875 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1876 sendreply(newrqref(r));
1878 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1884 rq->from->rqs[rq->rqid] = newrqref(rq);
1888 void rmclientrq(struct request *rq, uint8_t id) {
1891 r = rq->from->rqs[id];
1894 rq->from->rqs[id] = NULL;
1898 /* returns 0 if validation/authentication fails, else 1 */
1899 int radsrv(struct request *rq) {
1900 struct radmsg *msg = NULL;
1902 uint8_t *userascii = NULL;
1903 struct realm *realm = NULL;
1904 struct server *to = NULL;
1905 struct client *from = rq->from;
1907 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1912 debug(DBG_WARN, "radsrv: message validation failed, ignoring packet");
1919 memcpy(rq->rqauth, msg->auth, 16);
1921 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1922 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1923 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1927 if (!addclientrq(rq))
1930 if (msg->code == RAD_Status_Server) {
1931 respond(rq, RAD_Access_Accept, NULL);
1935 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1937 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1940 if (!dottl(msg, options.ttlattrtype, options.addttl)) {
1941 debug(DBG_WARN, "radsrv: ignoring request from client %s (%s), ttl exceeded", from->conf->name, addr2string(from->addr));
1945 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1947 if (msg->code == RAD_Accounting_Request) {
1948 acclog(msg, from->conf->host);
1949 respond(rq, RAD_Accounting_Response, NULL);
1951 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1955 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1956 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1960 userascii = radattr2ascii(attr);
1963 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1965 /* will return with lock on the realm */
1966 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1968 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1973 if (realm->message && msg->code == RAD_Access_Request) {
1974 debug(DBG_INFO, "radsrv: sending reject to %s for %s", from->conf->host, userascii);
1975 respond(rq, RAD_Access_Reject, realm->message);
1976 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1977 acclog(msg, from->conf->host);
1978 respond(rq, RAD_Accounting_Response, NULL);
1983 if (options.loopprevention && !strcmp(from->conf->name, to->conf->name)) {
1984 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s (%s) to server %s, discarding",
1985 from->conf->name, addr2string(from->addr), to->conf->name);
1989 if (msg->code == RAD_Accounting_Request)
1990 memset(msg->auth, 0, 16);
1991 else if (!RAND_bytes(msg->auth, 16)) {
1992 debug(DBG_WARN, "radsrv: failed to generate random auth");
1997 printfchars(NULL, "auth", "%02x ", auth, 16);
2000 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
2002 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
2003 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
2007 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
2009 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
2010 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
2014 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
2020 pthread_mutex_unlock(&realm->mutex);
2025 rmclientrq(rq, msg->id);
2030 pthread_mutex_unlock(&realm->mutex);
2036 void replyh(struct server *server, unsigned char *buf) {
2037 struct client *from;
2038 struct rqout *rqout;
2040 unsigned char *subattrs;
2041 uint8_t *username, *stationid, *replymsg;
2042 struct radmsg *msg = NULL;
2044 struct list_node *node;
2046 server->connectionok = 1;
2047 server->lostrqs = 0;
2049 rqout = server->requests + buf[1];
2050 pthread_mutex_lock(rqout->lock);
2051 if (!rqout->tries) {
2054 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
2058 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
2062 debug(DBG_WARN, "replyh: message validation failed, ignoring packet");
2065 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
2066 && msg->code != RAD_Accounting_Response) {
2067 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
2070 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
2072 gettimeofday(&server->lastrcv, NULL);
2074 if (rqout->rq->msg->code == RAD_Status_Server) {
2075 freerqoutdata(rqout);
2076 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2080 gettimeofday(&server->lastreply, NULL);
2081 from = rqout->rq->from;
2083 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
2084 debug(DBG_WARN, "replyh: rewritein failed");
2088 if (!dottl(msg, options.ttlattrtype, options.addttl)) {
2089 debug(DBG_WARN, "replyh: ignoring reply from server %s, ttl exceeded", server->conf->host);
2094 for (node = list_first(msg->attrs); node; node = list_next(node)) {
2095 attr = (struct tlv *)node->data;
2096 if (attr->t != RAD_Attr_Vendor_Specific)
2100 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
2103 sublen = attr->l - 4;
2104 subattrs = attr->v + 4;
2105 if (!attrvalidate(subattrs, sublen) ||
2106 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2107 rqout->rq, server->conf->secret, from->conf->secret) ||
2108 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2109 rqout->rq, server->conf->secret, from->conf->secret))
2113 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2117 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
2118 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
2120 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
2121 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
2124 debug(DBG_INFO, "%s for user %s stationid %s from %s (%s)",
2125 radmsgtype2string(msg->code), username, stationid, server->conf->host, replymsg);
2128 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2129 radmsgtype2string(msg->code), username, stationid, server->conf->host);
2133 debug(DBG_INFO, "%s for user %s from %s (%s)",
2134 radmsgtype2string(msg->code), username, server->conf->host, replymsg);
2137 debug(DBG_INFO, "%s for user %s from %s",
2138 radmsgtype2string(msg->code), username, server->conf->host);
2144 msg->id = (char)rqout->rq->rqid;
2145 memcpy(msg->auth, rqout->rq->rqauth, 16);
2148 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2151 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
2152 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
2153 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2156 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
2159 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
2160 debug(DBG_WARN, "replyh: rewriteout failed");
2164 debug(DBG_INFO, "replyh: passing reply to client %s (%s)", from->conf->name, addr2string(from->addr));
2165 radmsg_free(rqout->rq->msg);
2166 rqout->rq->msg = msg;
2167 sendreply(newrqref(rqout->rq));
2168 freerqoutdata(rqout);
2169 pthread_mutex_unlock(rqout->lock);
2174 pthread_mutex_unlock(rqout->lock);
2178 struct request *createstatsrvrq() {
2185 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
2188 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
2191 if (!radmsg_add(rq->msg, attr)) {
2202 /* code for removing state not finished */
2203 void *clientwr(void *arg) {
2204 struct server *server = (struct server *)arg;
2205 struct rqout *rqout = NULL;
2206 pthread_t clientrdth;
2207 int i, dynconffail = 0;
2210 struct timeval now, laststatsrv;
2211 struct timespec timeout;
2212 struct request *statsrvrq;
2213 struct clsrvconf *conf;
2215 conf = server->conf;
2217 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2222 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2223 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2227 memset(&timeout, 0, sizeof(struct timespec));
2229 if (conf->statusserver) {
2230 gettimeofday(&server->lastrcv, NULL);
2231 gettimeofday(&laststatsrv, NULL);
2234 if (conf->pdef->connecter) {
2235 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2237 server->connectionok = 1;
2238 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
2239 debug(DBG_ERR, "clientwr: pthread_create failed");
2243 server->connectionok = 1;
2246 pthread_mutex_lock(&server->newrq_mutex);
2247 if (!server->newrq) {
2248 gettimeofday(&now, NULL);
2249 /* random 0-7 seconds */
2250 RAND_bytes(&rnd, 1);
2252 if (conf->statusserver) {
2253 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2254 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
2256 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
2257 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
2259 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2260 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2263 if (timeout.tv_sec > now.tv_sec)
2264 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2266 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2269 if (server->newrq) {
2270 debug(DBG_DBG, "clientwr: got new request");
2275 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2277 pthread_mutex_unlock(&server->newrq_mutex);
2279 for (i = 0; i < MAX_REQUESTS; i++) {
2280 if (server->clientrdgone) {
2281 pthread_join(clientrdth, NULL);
2285 for (; i < MAX_REQUESTS; i++) {
2286 rqout = server->requests + i;
2288 pthread_mutex_lock(rqout->lock);
2291 pthread_mutex_unlock(rqout->lock);
2295 if (i == MAX_REQUESTS)
2298 gettimeofday(&now, NULL);
2299 if (now.tv_sec < rqout->expiry.tv_sec) {
2300 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2301 timeout.tv_sec = rqout->expiry.tv_sec;
2302 pthread_mutex_unlock(rqout->lock);
2306 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2307 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2308 if (conf->statusserver) {
2309 if (*rqout->rq->buf == RAD_Status_Server) {
2310 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2311 if (server->lostrqs < 255)
2315 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2316 if (server->lostrqs < 255)
2319 freerqoutdata(rqout);
2320 pthread_mutex_unlock(rqout->lock);
2324 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2325 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2326 timeout.tv_sec = rqout->expiry.tv_sec;
2328 conf->pdef->clientradput(server, rqout->rq->buf);
2329 pthread_mutex_unlock(rqout->lock);
2331 if (conf->statusserver && server->connectionok) {
2332 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2333 gettimeofday(&now, NULL);
2334 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
2336 statsrvrq = createstatsrvrq();
2338 statsrvrq->to = server;
2339 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2346 conf->servers = NULL;
2347 if (server->dynamiclookuparg) {
2348 removeserversubrealms(realms, conf);
2352 freeclsrvconf(conf);
2354 freeserver(server, 1);
2355 ERR_remove_state(0);
2359 void createlistener(uint8_t type, char *arg) {
2361 struct clsrvconf *listenres;
2362 struct addrinfo *res;
2363 int s = -1, on = 1, *sp = NULL;
2365 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2367 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2369 for (res = listenres->addrinfo; res; res = res->ai_next) {
2370 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2372 debug(DBG_WARN, "createlistener: socket failed");
2375 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2377 if (res->ai_family == AF_INET6)
2378 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2380 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2381 debug(DBG_WARN, "createlistener: bind failed");
2387 sp = malloc(sizeof(int));
2389 debugx(1, DBG_ERR, "malloc failed");
2391 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
2392 debugx(1, DBG_ERR, "pthread_create failed");
2396 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2398 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
2399 listenres->host ? listenres->host : "*", listenres->port);
2400 freeclsrvres(listenres);
2403 void createlisteners(uint8_t type, char **args) {
2407 for (i = 0; args[i]; i++)
2408 createlistener(type, args[i]);
2410 createlistener(type, NULL);
2414 void ssl_info_callback(const SSL *ssl, int where, int ret) {
2418 w = where & ~SSL_ST_MASK;
2420 if (w & SSL_ST_CONNECT)
2422 else if (w & SSL_ST_ACCEPT)
2427 if (where & SSL_CB_LOOP)
2428 debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
2429 else if (where & SSL_CB_ALERT) {
2430 s = (where & SSL_CB_READ) ? "read" : "write";
2431 debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
2433 else if (where & SSL_CB_EXIT) {
2435 debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
2437 debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
2447 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2448 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2449 for (i = 0; i < CRYPTO_num_locks(); i++) {
2450 ssl_lock_count[i] = 0;
2451 pthread_mutex_init(&ssl_locks[i], NULL);
2453 CRYPTO_set_id_callback(ssl_thread_id);
2454 CRYPTO_set_locking_callback(ssl_locking_callback);
2456 SSL_load_error_strings();
2459 while (!RAND_status()) {
2462 RAND_seed((unsigned char *)&t, sizeof(time_t));
2463 RAND_seed((unsigned char *)&pid, sizeof(pid));
2467 X509_VERIFY_PARAM *createverifyparams(char **poids) {
2468 X509_VERIFY_PARAM *pm;
2469 ASN1_OBJECT *pobject;
2472 pm = X509_VERIFY_PARAM_new();
2476 for (i = 0; poids[i]; i++) {
2477 pobject = OBJ_txt2obj(poids[i], 0);
2479 X509_VERIFY_PARAM_free(pm);
2482 X509_VERIFY_PARAM_add0_policy(pm, pobject);
2485 X509_VERIFY_PARAM_set_flags(pm, X509_V_FLAG_POLICY_CHECK | X509_V_FLAG_EXPLICIT_POLICY);
2489 int tlsaddcacrl(SSL_CTX *ctx, struct tls *conf) {
2490 STACK_OF(X509_NAME) *calist;
2492 unsigned long error;
2494 if (!SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2495 while ((error = ERR_get_error()))
2496 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2497 debug(DBG_ERR, "tlsaddcacrl: Error updating TLS context %s", conf->name);
2501 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2502 if (!conf->cacertfile || calist) {
2503 if (conf->cacertpath) {
2505 calist = sk_X509_NAME_new_null();
2506 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2507 sk_X509_NAME_free(calist);
2513 while ((error = ERR_get_error()))
2514 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2515 debug(DBG_ERR, "tlsaddcacrl: Error adding CA subjects in TLS context %s", conf->name);
2518 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2519 SSL_CTX_set_client_CA_list(ctx, calist);
2521 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2522 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2524 if (conf->crlcheck || conf->vpm) {
2525 x509_s = SSL_CTX_get_cert_store(ctx);
2527 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2529 X509_STORE_set1_param(x509_s, conf->vpm);
2532 debug(DBG_DBG, "tlsaddcacrl: updated TLS context %s", conf->name);
2536 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2537 SSL_CTX *ctx = NULL;
2538 unsigned long error;
2545 ctx = SSL_CTX_new(TLSv1_method());
2547 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2551 ctx = SSL_CTX_new(DTLSv1_method());
2553 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2555 SSL_CTX_set_read_ahead(ctx, 1);
2559 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2563 if (conf->certkeypwd) {
2564 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2565 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2567 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2568 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2569 !SSL_CTX_check_private_key(ctx)) {
2570 while ((error = ERR_get_error()))
2571 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2572 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2577 if (conf->policyoids) {
2579 conf->vpm = createverifyparams(conf->policyoids);
2581 debug(DBG_ERR, "tlsaddcacrl: Failed to add policyOIDs in TLS context %s", conf->name);
2588 if (!tlsaddcacrl(ctx, conf)) {
2590 X509_VERIFY_PARAM_free(conf->vpm);
2597 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
2601 struct tls *tlsgettls(char *alt1, char *alt2) {
2604 t = hash_read(tlsconfs, alt1, strlen(alt1));
2606 t = hash_read(tlsconfs, alt2, strlen(alt2));
2610 SSL_CTX *tlsgetctx(uint8_t type, struct tls *t) {
2615 gettimeofday(&now, NULL);
2619 if (t->tlsexpiry && t->tlsctx) {
2620 if (t->tlsexpiry < now.tv_sec) {
2621 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
2622 tlsaddcacrl(t->tlsctx, t);
2626 t->tlsctx = tlscreatectx(RAD_TLS, t);
2628 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
2632 if (t->dtlsexpiry && t->dtlsctx) {
2633 if (t->dtlsexpiry < now.tv_sec) {
2634 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
2635 tlsaddcacrl(t->dtlsctx, t);
2639 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2641 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
2648 struct list *addsrvconfs(char *value, char **names) {
2649 struct list *conflist;
2651 struct list_node *entry;
2652 struct clsrvconf *conf = NULL;
2654 if (!names || !*names)
2657 conflist = list_create();
2659 debug(DBG_ERR, "malloc failed");
2663 for (n = 0; names[n]; n++) {
2664 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2665 conf = (struct clsrvconf *)entry->data;
2666 if (!strcasecmp(names[n], conf->name))
2670 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2671 list_destroy(conflist);
2674 if (!list_push(conflist, conf)) {
2675 debug(DBG_ERR, "malloc failed");
2676 list_destroy(conflist);
2679 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2684 void freerealm(struct realm *realm) {
2687 debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2688 if (--realm->refcount)
2692 free(realm->message);
2693 regfree(&realm->regex);
2694 pthread_mutex_destroy(&realm->mutex);
2695 /* if refcount == 0, all subrealms gone */
2696 list_destroy(realm->subrealms);
2697 /* if refcount == 0, all srvconfs gone */
2698 list_destroy(realm->srvconfs);
2699 /* if refcount == 0, all accsrvconfs gone */
2700 list_destroy(realm->accsrvconfs);
2701 freerealm(realm->parent);
2705 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2707 struct realm *realm;
2708 char *s, *regex = NULL;
2710 if (*value == '/') {
2711 /* regexp, remove optional trailing / if present */
2712 if (value[strlen(value) - 1] == '/')
2713 value[strlen(value) - 1] = '\0';
2715 /* not a regexp, let us make it one */
2716 if (*value == '*' && !value[1])
2717 regex = stringcopy(".*", 0);
2719 for (n = 0, s = value; *s;)
2722 regex = malloc(strlen(value) + n + 3);
2725 for (n = 1, s = value; *s; s++) {
2735 debug(DBG_ERR, "malloc failed");
2739 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2742 realm = malloc(sizeof(struct realm));
2744 debug(DBG_ERR, "malloc failed");
2747 memset(realm, 0, sizeof(struct realm));
2749 if (pthread_mutex_init(&realm->mutex, NULL)) {
2750 debug(DBG_ERR, "mutex init failed");
2756 realm->name = stringcopy(value, 0);
2758 debug(DBG_ERR, "malloc failed");
2761 if (message && strlen(message) > 253) {
2762 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2765 realm->message = message;
2766 realm->accresp = accresp;
2768 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2769 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2773 if (servers && *servers) {
2774 realm->srvconfs = addsrvconfs(value, servers);
2775 if (!realm->srvconfs)
2779 if (accservers && *accservers) {
2780 realm->accsrvconfs = addsrvconfs(value, accservers);
2781 if (!realm->accsrvconfs)
2785 if (!list_push(realmlist, realm)) {
2786 debug(DBG_ERR, "malloc failed");
2787 pthread_mutex_destroy(&realm->mutex);
2791 debug(DBG_DBG, "addrealm: added realm %s", value);
2795 while (list_shift(realm->srvconfs));
2796 while (list_shift(realm->accsrvconfs));
2803 for (n = 0; servers[n]; n++)
2805 freegconfmstr(servers);
2809 for (n = 0; accservers[n]; n++)
2811 freegconfmstr(accservers);
2813 return newrealmref(realm);
2816 struct realm *adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2817 struct clsrvconf *srvconf;
2818 struct realm *newrealm = NULL;
2819 char *realmname, *s;
2822 if (!conf->dynamiclookupcommand)
2825 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2826 realmname = strrchr(id, '@');
2832 for (s = realmname; *s; s++)
2833 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2836 srvconf = malloc(sizeof(struct clsrvconf));
2838 debug(DBG_ERR, "malloc failed");
2842 if (!addserver(srvconf))
2845 if (!realm->subrealms)
2846 realm->subrealms = list_create();
2847 if (!realm->subrealms)
2849 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2852 newrealm->parent = newrealmref(realm);
2854 /* add server and accserver to newrealm */
2855 newrealm->srvconfs = list_create();
2856 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2857 debug(DBG_ERR, "malloc failed");
2860 newrealmref(newrealm);
2861 newrealm->accsrvconfs = list_create();
2862 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2863 debug(DBG_ERR, "malloc failed");
2864 list_shift(realm->srvconfs);
2865 freerealm(newrealm);
2868 newrealmref(newrealm);
2870 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2871 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2872 debug(DBG_ERR, "pthread_create failed");
2873 list_shift(realm->srvconfs);
2874 freerealm(newrealm);
2875 list_shift(realm->accsrvconfs);
2876 freerealm(newrealm);
2879 pthread_detach(clientth);
2884 list_removedata(realm->subrealms, newrealm);
2885 freerealm(newrealm);
2886 if (!list_first(realm->subrealms)) {
2887 list_destroy(realm->subrealms);
2888 realm->subrealms = NULL;
2891 freeserver(srvconf->servers, 1);
2893 debug(DBG_ERR, "failed to create dynamic server");
2897 int dynamicconfig(struct server *server) {
2898 int ok, fd[2], status;
2900 struct clsrvconf *conf = server->conf;
2901 struct gconffile *cf = NULL;
2903 /* for now we only learn hostname/address */
2904 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2907 debug(DBG_ERR, "dynamicconfig: pipe error");
2912 debug(DBG_ERR, "dynamicconfig: fork error");
2916 } else if (pid == 0) {
2919 if (fd[1] != STDOUT_FILENO) {
2920 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2921 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2924 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2925 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2929 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2930 ok = getgenericconfig(&cf, NULL,
2931 "Server", CONF_CBK, confserver_cb, (void *)conf,
2936 if (waitpid(pid, &status, 0) < 0) {
2937 debug(DBG_ERR, "dynamicconfig: wait error");
2942 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2950 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2954 int addmatchcertattr(struct clsrvconf *conf) {
2958 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2959 r = &conf->certcnregex;
2960 v = conf->matchcertattr + 4;
2961 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2962 r = &conf->certuriregex;
2963 v = conf->matchcertattr + 20;
2968 /* regexp, remove optional trailing / if present */
2969 if (v[strlen(v) - 1] == '/')
2970 v[strlen(v) - 1] = '\0';
2974 *r = malloc(sizeof(regex_t));
2976 debug(DBG_ERR, "malloc failed");
2979 if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2982 debug(DBG_ERR, "failed to compile regular expression %s", v);
2988 /* should accept both names and numeric values, only numeric right now */
2989 uint8_t attrname2val(char *attrname) {
2992 val = atoi(attrname);
2993 return val > 0 && val < 256 ? val : 0;
2996 /* should accept both names and numeric values, only numeric right now */
2997 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
3000 *vendor = atoi(attrname);
3001 s = strchr(attrname, ':');
3006 *type = atoi(s + 1);
3007 return *type >= 0 && *type < 256;
3010 /* should accept both names and numeric values, only numeric right now */
3011 struct tlv *extractattr(char *nameval) {
3016 s = strchr(nameval, ':');
3017 name = atoi(nameval);
3018 if (!s || name < 1 || name > 255)
3020 len = strlen(s + 1);
3023 a = malloc(sizeof(struct tlv));
3026 a->v = (uint8_t *)stringcopy(s + 1, 0);
3036 /* should accept both names and numeric values, only numeric right now */
3037 struct modattr *extractmodattr(char *nameval) {
3042 if (!strncasecmp(nameval, "User-Name:/", 11)) {
3046 s = strchr(nameval, ':');
3047 name = atoi(nameval);
3048 if (!s || name < 1 || name > 255 || s[1] != '/')
3052 /* regexp, remove optional trailing / if present */
3053 if (s[strlen(s) - 1] == '/')
3054 s[strlen(s) - 1] = '\0';
3062 m = malloc(sizeof(struct modattr));
3064 debug(DBG_ERR, "malloc failed");
3069 m->replacement = stringcopy(t, 0);
3070 if (!m->replacement) {
3072 debug(DBG_ERR, "malloc failed");
3076 m->regex = malloc(sizeof(regex_t));
3078 free(m->replacement);
3080 debug(DBG_ERR, "malloc failed");
3084 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
3086 free(m->replacement);
3088 debug(DBG_ERR, "failed to compile regular expression %s", s);
3095 struct rewrite *getrewrite(char *alt1, char *alt2) {
3098 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
3100 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
3105 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
3106 struct rewrite *rewrite = NULL;
3108 uint8_t *rma = NULL;
3109 uint32_t *p, *rmva = NULL;
3110 struct list *adda = NULL, *moda = NULL;
3115 for (n = 0; rmattrs[n]; n++);
3116 rma = calloc(n + 1, sizeof(uint8_t));
3118 debugx(1, DBG_ERR, "malloc failed");
3120 for (i = 0; i < n; i++)
3121 if (!(rma[i] = attrname2val(rmattrs[i])))
3122 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
3123 freegconfmstr(rmattrs);
3128 for (n = 0; rmvattrs[n]; n++);
3129 rmva = calloc(2 * n + 1, sizeof(uint32_t));
3131 debugx(1, DBG_ERR, "malloc failed");
3133 for (p = rmva, i = 0; i < n; i++, p += 2)
3134 if (!vattrname2val(rmvattrs[i], p, p + 1))
3135 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
3136 freegconfmstr(rmvattrs);
3141 adda = list_create();
3143 debugx(1, DBG_ERR, "malloc failed");
3144 for (i = 0; addattrs[i]; i++) {
3145 a = extractattr(addattrs[i]);
3147 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
3148 if (!list_push(adda, a))
3149 debugx(1, DBG_ERR, "malloc failed");
3151 freegconfmstr(addattrs);
3155 moda = list_create();
3157 debugx(1, DBG_ERR, "malloc failed");
3158 for (i = 0; modattrs[i]; i++) {
3159 m = extractmodattr(modattrs[i]);
3161 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
3162 if (!list_push(moda, m))
3163 debugx(1, DBG_ERR, "malloc failed");
3165 freegconfmstr(modattrs);
3168 if (rma || rmva || adda || moda) {
3169 rewrite = malloc(sizeof(struct rewrite));
3171 debugx(1, DBG_ERR, "malloc failed");
3172 rewrite->removeattrs = rma;
3173 rewrite->removevendorattrs = rmva;
3174 rewrite->addattrs = adda;
3175 rewrite->modattrs = moda;
3178 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
3179 debugx(1, DBG_ERR, "malloc failed");
3180 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3183 int setttlattr(struct options *opts, char *defaultattr) {
3184 char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
3186 if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
3187 (opts->ttlattrtype[1] != -1 || opts->ttlattrtype[0] < 256))
3189 debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
3193 void freeclsrvconf(struct clsrvconf *conf) {
3199 free(conf->matchcertattr);
3200 if (conf->certcnregex)
3201 regfree(conf->certcnregex);
3202 if (conf->certuriregex)
3203 regfree(conf->certuriregex);
3204 free(conf->confrewritein);
3205 free(conf->confrewriteout);
3206 if (conf->rewriteusername) {
3207 if (conf->rewriteusername->regex)
3208 regfree(conf->rewriteusername->regex);
3209 free(conf->rewriteusername->replacement);
3210 free(conf->rewriteusername);
3212 free(conf->dynamiclookupcommand);
3213 free(conf->rewritein);
3214 free(conf->rewriteout);
3216 freeaddrinfo(conf->addrinfo);
3218 pthread_mutex_destroy(conf->lock);
3221 /* not touching ssl_ctx, clients and servers */
3225 int mergeconfstring(char **dst, char **src) {
3234 t = stringcopy(*dst, 0);
3236 debug(DBG_ERR, "malloc failed");
3244 /* assumes dst is a shallow copy */
3245 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3246 if (!mergeconfstring(&dst->name, &src->name) ||
3247 !mergeconfstring(&dst->host, &src->host) ||
3248 !mergeconfstring(&dst->port, &src->port) ||
3249 !mergeconfstring(&dst->secret, &src->secret) ||
3250 !mergeconfstring(&dst->tls, &src->tls) ||
3251 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3252 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
3253 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
3254 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3257 dst->pdef = src->pdef;
3258 dst->statusserver = src->statusserver;
3259 dst->certnamecheck = src->certnamecheck;
3260 if (src->retryinterval != 255)
3261 dst->retryinterval = src->retryinterval;
3262 if (src->retrycount != 255)
3263 dst->retrycount = src->retrycount;
3267 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3268 struct clsrvconf *conf;
3269 char *conftype = NULL, *rewriteinalias = NULL;
3270 long int dupinterval = LONG_MIN;
3272 debug(DBG_DBG, "confclient_cb called for %s", block);
3274 conf = malloc(sizeof(struct clsrvconf));
3276 debugx(1, DBG_ERR, "malloc failed");
3277 memset(conf, 0, sizeof(struct clsrvconf));
3278 conf->certnamecheck = 1;
3280 if (!getgenericconfig(cf, block,
3281 "type", CONF_STR, &conftype,
3282 "host", CONF_STR, &conf->host,
3283 "secret", CONF_STR, &conf->secret,
3284 "tls", CONF_STR, &conf->tls,
3285 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3286 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3287 "DuplicateInterval", CONF_LINT, &dupinterval,
3288 "rewrite", CONF_STR, &rewriteinalias,
3289 "rewriteIn", CONF_STR, &conf->confrewritein,
3290 "rewriteOut", CONF_STR, &conf->confrewriteout,
3291 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
3294 debugx(1, DBG_ERR, "configuration error");
3296 conf->name = stringcopy(val, 0);
3298 conf->host = stringcopy(val, 0);
3299 if (!conf->name || !conf->host)
3300 debugx(1, DBG_ERR, "malloc failed");
3303 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3304 conf->type = protoname2int(conftype);
3305 conf->pdef = &protodefs[conf->type];
3306 if (!conf->pdef->name)
3307 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3310 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3311 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
3313 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3314 if (conf->matchcertattr && !addmatchcertattr(conf))
3315 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3318 if (dupinterval != LONG_MIN) {
3319 if (dupinterval < 0 || dupinterval > 255)
3320 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
3321 conf->dupinterval = (uint8_t)dupinterval;
3323 conf->dupinterval = conf->pdef->duplicateintervaldefault;
3325 if (!conf->confrewritein)
3326 conf->confrewritein = rewriteinalias;
3328 free(rewriteinalias);
3329 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
3330 if (conf->confrewriteout)
3331 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3333 if (conf->confrewriteusername) {
3334 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
3335 if (!conf->rewriteusername)
3336 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3339 if (!resolvepeer(conf, 0))
3340 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3342 if (!conf->secret) {
3343 if (!conf->pdef->secretdefault)
3344 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3345 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3347 debugx(1, DBG_ERR, "malloc failed");
3350 conf->lock = malloc(sizeof(pthread_mutex_t));
3352 debugx(1, DBG_ERR, "malloc failed");
3354 pthread_mutex_init(conf->lock, NULL);
3355 if (!list_push(clconfs, conf))
3356 debugx(1, DBG_ERR, "malloc failed");
3360 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3361 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3362 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
3363 if (!conf->tlsconf) {
3364 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3367 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3368 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3374 conf->port = stringcopy(conf->pdef->portdefault, 0);
3376 debug(DBG_ERR, "malloc failed");
3381 if (conf->retryinterval == 255)
3382 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3383 if (conf->retrycount == 255)
3384 conf->retrycount = protodefs[conf->type].retrycountdefault;
3386 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
3387 if (conf->confrewriteout)
3388 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3390 if (!conf->secret) {
3391 if (!conf->pdef->secretdefault) {
3392 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3395 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3396 if (!conf->secret) {
3397 debug(DBG_ERR, "malloc failed");
3402 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3403 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3409 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3410 struct clsrvconf *conf, *resconf;
3411 char *conftype = NULL, *rewriteinalias = NULL;
3412 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3414 debug(DBG_DBG, "confserver_cb called for %s", block);
3416 conf = malloc(sizeof(struct clsrvconf));
3418 debug(DBG_ERR, "malloc failed");
3421 memset(conf, 0, sizeof(struct clsrvconf));
3422 resconf = (struct clsrvconf *)arg;
3424 conf->statusserver = resconf->statusserver;
3425 conf->certnamecheck = resconf->certnamecheck;
3427 conf->certnamecheck = 1;
3429 if (!getgenericconfig(cf, block,
3430 "type", CONF_STR, &conftype,
3431 "host", CONF_STR, &conf->host,
3432 "port", CONF_STR, &conf->port,
3433 "secret", CONF_STR, &conf->secret,
3434 "tls", CONF_STR, &conf->tls,
3435 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3436 "rewrite", CONF_STR, &rewriteinalias,
3437 "rewriteIn", CONF_STR, &conf->confrewritein,
3438 "rewriteOut", CONF_STR, &conf->confrewriteout,
3439 "StatusServer", CONF_BLN, &conf->statusserver,
3440 "RetryInterval", CONF_LINT, &retryinterval,
3441 "RetryCount", CONF_LINT, &retrycount,
3442 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3443 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3446 debug(DBG_ERR, "configuration error");
3450 conf->name = stringcopy(val, 0);
3452 debug(DBG_ERR, "malloc failed");
3456 conf->host = stringcopy(val, 0);
3458 debug(DBG_ERR, "malloc failed");
3464 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3465 conf->type = protoname2int(conftype);
3466 conf->pdef = &protodefs[conf->type];
3467 if (!conf->pdef->name) {
3468 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3474 if (!conf->confrewritein)
3475 conf->confrewritein = rewriteinalias;
3477 free(rewriteinalias);
3478 rewriteinalias = NULL;
3480 if (retryinterval != LONG_MIN) {
3481 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3482 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3485 conf->retryinterval = (uint8_t)retryinterval;
3487 conf->retryinterval = 255;
3489 if (retrycount != LONG_MIN) {
3490 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3491 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3494 conf->retrycount = (uint8_t)retrycount;
3496 conf->retrycount = 255;
3499 if (!mergesrvconf(resconf, conf))
3503 if (conf->dynamiclookupcommand) {
3504 free(conf->dynamiclookupcommand);
3505 conf->dynamiclookupcommand = NULL;
3509 if (resconf || !conf->dynamiclookupcommand) {
3510 if (!compileserverconfig(conf, block))
3517 if (!list_push(srvconfs, conf)) {
3518 debug(DBG_ERR, "malloc failed");
3525 free(rewriteinalias);
3526 freeclsrvconf(conf);
3530 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3531 char **servers = NULL, **accservers = NULL, *msg = NULL;
3532 uint8_t accresp = 0;
3534 debug(DBG_DBG, "confrealm_cb called for %s", block);
3536 if (!getgenericconfig(cf, block,
3537 "server", CONF_MSTR, &servers,
3538 "accountingServer", CONF_MSTR, &accservers,
3539 "ReplyMessage", CONF_STR, &msg,
3540 "AccountingResponse", CONF_BLN, &accresp,
3543 debugx(1, DBG_ERR, "configuration error");
3545 addrealm(realms, val, servers, accservers, msg, accresp);
3549 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3551 long int expiry = LONG_MIN;
3553 debug(DBG_DBG, "conftls_cb called for %s", block);
3555 conf = malloc(sizeof(struct tls));
3557 debug(DBG_ERR, "conftls_cb: malloc failed");
3560 memset(conf, 0, sizeof(struct tls));
3562 if (!getgenericconfig(cf, block,
3563 "CACertificateFile", CONF_STR, &conf->cacertfile,
3564 "CACertificatePath", CONF_STR, &conf->cacertpath,
3565 "CertificateFile", CONF_STR, &conf->certfile,
3566 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3567 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3568 "CacheExpiry", CONF_LINT, &expiry,
3569 "CRLCheck", CONF_BLN, &conf->crlcheck,
3570 "PolicyOID", CONF_MSTR, &conf->policyoids,
3573 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3576 if (!conf->certfile || !conf->certkeyfile) {
3577 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3580 if (!conf->cacertfile && !conf->cacertpath) {
3581 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3584 if (expiry != LONG_MIN) {
3586 debug(DBG_ERR, "error in block %s, value of option CacheExpiry is %ld, may not be negative", val, expiry);
3589 conf->cacheexpiry = expiry;
3592 conf->name = stringcopy(val, 0);
3594 debug(DBG_ERR, "conftls_cb: malloc failed");
3598 if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
3599 debug(DBG_ERR, "conftls_cb: malloc failed");
3602 if (!tlsgetctx(RAD_TLS, conf))
3603 debug(DBG_ERR, "conftls_cb: error creating ctx for TLS block %s", val);
3604 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3608 free(conf->cacertfile);
3609 free(conf->cacertpath);
3610 free(conf->certfile);
3611 free(conf->certkeyfile);
3612 free(conf->certkeypwd);
3613 freegconfmstr(conf->policyoids);
3618 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3619 char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3621 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3623 if (!getgenericconfig(cf, block,
3624 "removeAttribute", CONF_MSTR, &rmattrs,
3625 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3626 "addAttribute", CONF_MSTR, &addattrs,
3627 "modifyAttribute", CONF_MSTR, &modattrs,
3630 debugx(1, DBG_ERR, "configuration error");
3631 addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3635 void getmainconfig(const char *configfile) {
3636 long int addttl = LONG_MIN, loglevel = LONG_MIN;
3637 struct gconffile *cfs;
3639 cfs = openconfigfile(configfile);
3640 memset(&options, 0, sizeof(options));
3642 clconfs = list_create();
3644 debugx(1, DBG_ERR, "malloc failed");
3646 srvconfs = list_create();
3648 debugx(1, DBG_ERR, "malloc failed");
3650 realms = list_create();
3652 debugx(1, DBG_ERR, "malloc failed");
3654 tlsconfs = hash_create();
3656 debugx(1, DBG_ERR, "malloc failed");
3658 rewriteconfs = hash_create();
3660 debugx(1, DBG_ERR, "malloc failed");
3662 if (!getgenericconfig(&cfs, NULL,
3663 "ListenUDP", CONF_MSTR, &options.listenargs[RAD_UDP],
3664 "ListenTCP", CONF_MSTR, &options.listenargs[RAD_TCP],
3665 "ListenTLS", CONF_MSTR, &options.listenargs[RAD_TLS],
3666 "ListenDTLS", CONF_MSTR, &options.listenargs[RAD_DTLS],
3667 "SourceUDP", CONF_STR, &options.sourcearg[RAD_UDP],
3668 "SourceTCP", CONF_STR, &options.sourcearg[RAD_TCP],
3669 "SourceTLS", CONF_STR, &options.sourcearg[RAD_TLS],
3670 "SourceDTLS", CONF_STR, &options.sourcearg[RAD_DTLS],
3671 "TTLAttribute", CONF_STR, &options.ttlattr,
3672 "addTTL", CONF_LINT, &addttl,
3673 "LogLevel", CONF_LINT, &loglevel,
3674 "LogDestination", CONF_STR, &options.logdestination,
3675 "LoopPrevention", CONF_BLN, &options.loopprevention,
3676 "Client", CONF_CBK, confclient_cb, NULL,
3677 "Server", CONF_CBK, confserver_cb, NULL,
3678 "Realm", CONF_CBK, confrealm_cb, NULL,
3679 "TLS", CONF_CBK, conftls_cb, NULL,
3680 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3683 debugx(1, DBG_ERR, "configuration error");
3685 if (loglevel != LONG_MIN) {
3686 if (loglevel < 1 || loglevel > 4)
3687 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3688 options.loglevel = (uint8_t)loglevel;
3690 if (addttl != LONG_MIN) {
3691 if (addttl < 1 || addttl > 255)
3692 debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3693 options.addttl = (uint8_t)addttl;
3695 if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3696 debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3699 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3702 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3705 *configfile = optarg;
3708 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3709 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3710 *loglevel = *optarg - '0';
3719 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3724 if (!(argc - optind))
3728 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3732 int daemon(int a, int b) {
3740 for (i = 0; i < 3; i++) {
3742 open("/dev/null", O_RDWR);
3748 void *sighandler(void *arg) {
3753 sigemptyset(&sigset);
3754 sigaddset(&sigset, SIGPIPE);
3755 sigwait(&sigset, &sig);
3756 /* only get SIGPIPE right now, so could simplify below code */
3759 /* completely ignoring this */
3762 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3765 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3770 int main(int argc, char **argv) {
3773 struct list_node *entry;
3774 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3775 char *configfile = NULL;
3776 struct clsrvconf *srvconf;
3779 debug_init("radsecproxy");
3780 debug_set_level(DEBUG_LEVEL);
3782 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3784 debug_set_level(loglevel);
3785 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3787 options.loglevel = loglevel;
3788 else if (options.loglevel)
3789 debug_set_level(options.loglevel);
3791 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3792 free(options.logdestination);
3794 if (!list_first(clconfs))
3795 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3796 if (!list_first(realms))
3797 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3800 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3802 if (!foreground && (daemon(0, 0) < 0))
3803 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3805 debug_timestamp_on();
3806 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3808 sigemptyset(&sigset);
3809 /* exit on all but SIGPIPE, ignore more? */
3810 sigaddset(&sigset, SIGPIPE);
3811 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3812 pthread_create(&sigth, NULL, sighandler, NULL);
3814 memset(srcprotores, 0, sizeof(srcprotores));
3815 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3816 srvconf = (struct clsrvconf *)entry->data;
3817 if (srvconf->dynamiclookupcommand)
3819 if (!addserver(srvconf))
3820 debugx(1, DBG_ERR, "failed to add server");
3821 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3822 (void *)(srvconf->servers)))
3823 debugx(1, DBG_ERR, "pthread_create failed");
3826 for (i = 0; protodefs[i].name; i++) {
3827 if (protodefs[i].freesrcprotores && srcprotores[i]) {
3828 freeaddrinfo(srcprotores[i]);
3829 srcprotores[i] = NULL;
3831 if (protodefs[i].initextra)
3832 protodefs[i].initextra();
3833 if (find_clconf_type(i, NULL))
3834 createlisteners(i, options.listenargs[i]);
3837 /* just hang around doing nothing, anything to do here? */