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 &options.sourceudp, /* srcaddrport */
114 NULL, /* connecter */
115 NULL, /* clientconnreader */
116 clientradputudp, /* clientradput */
117 addclientudp, /* addclient */
118 addserverextraudp, /* addserverextra */
119 1, /* freesrcprotores */
120 initextraudp /* initextra */
122 { "tls", /* TLS, assuming RAD_TLS defined as 1 */
123 "mysecret", /* secretdefault */
124 SOCK_STREAM, /* socktype */
125 "2083", /* portdefault */
126 0, /* retrycountdefault */
127 0, /* retrycountmax */
128 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
129 60, /* retryintervalmax */
130 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
131 tlslistener, /* listener */
132 &options.sourcetls, /* srcaddrport */
133 tlsconnect, /* connecter */
134 tlsclientrd, /* clientconnreader */
135 clientradputtls, /* clientradput */
136 NULL, /* addclient */
137 NULL, /* addserverextra */
138 0, /* freesrcprotores */
141 { "tcp", /* TCP, assuming RAD_TCP defined as 2 */
142 NULL, /* secretdefault */
143 SOCK_STREAM, /* socktype */
144 "1812", /* portdefault */
145 0, /* retrycountdefault */
146 0, /* retrycountmax */
147 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
148 60, /* retryintervalmax */
149 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
150 tcplistener, /* listener */
151 &options.sourcetcp, /* srcaddrport */
152 tcpconnect, /* connecter */
153 tcpclientrd, /* clientconnreader */
154 clientradputtcp, /* clientradput */
155 NULL, /* addclient */
156 NULL, /* addserverextra */
157 0, /* freesrcprotores */
160 { "dtls", /* DTLS, assuming RAD_DTLS defined as 3 */
161 "mysecret", /* secretdefault */
162 SOCK_DGRAM, /* socktype */
163 "2083", /* portdefault */
164 REQUEST_RETRY_COUNT, /* retrycountdefault */
165 10, /* retrycountmax */
166 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
167 60, /* retryintervalmax */
168 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
169 udpdtlsserverrd, /* listener */
170 &options.sourcedtls, /* srcaddrport */
171 dtlsconnect, /* connecter */
172 dtlsclientrd, /* clientconnreader */
173 clientradputdtls, /* clientradput */
174 NULL, /* addclient */
175 addserverextradtls, /* addserverextra */
176 1, /* freesrcprotores */
177 initextradtls /* initextra */
183 uint8_t protoname2int(const char *name) {
186 for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
190 /* callbacks for making OpenSSL thread safe */
191 unsigned long ssl_thread_id() {
192 return (unsigned long)pthread_self();
195 void ssl_locking_callback(int mode, int type, const char *file, int line) {
196 if (mode & CRYPTO_LOCK) {
197 pthread_mutex_lock(&ssl_locks[type]);
198 ssl_lock_count[type]++;
200 pthread_mutex_unlock(&ssl_locks[type]);
203 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
204 int pwdlen = strlen(userdata);
205 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
207 memcpy(buf, userdata, pwdlen);
211 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
216 err_cert = X509_STORE_CTX_get_current_cert(ctx);
217 err = X509_STORE_CTX_get_error(ctx);
218 depth = X509_STORE_CTX_get_error_depth(ctx);
220 if (depth > MAX_CERT_DEPTH) {
222 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
223 X509_STORE_CTX_set_error(ctx, err);
228 buf = X509_NAME_oneline(X509_get_subject_name(err_cert), NULL, 0);
229 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf ? buf : "");
234 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
236 buf = X509_NAME_oneline(X509_get_issuer_name(err_cert), NULL, 0);
238 debug(DBG_WARN, "\tIssuer=%s", buf);
244 case X509_V_ERR_CERT_NOT_YET_VALID:
245 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
246 debug(DBG_WARN, "\tCertificate not yet valid");
248 case X509_V_ERR_CERT_HAS_EXPIRED:
249 debug(DBG_WARN, "Certificate has expired");
251 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
252 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
254 case X509_V_ERR_NO_EXPLICIT_POLICY:
255 debug(DBG_WARN, "No Explicit Certificate Policy");
260 printf("certificate verify returns %d\n", ok);
265 struct addrinfo *getsrcprotores(uint8_t type) {
266 return srcprotores[type];
269 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
270 struct addrinfo hints, *addrinfo, *res;
274 slash = conf->host ? strchr(conf->host, '/') : NULL;
278 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
282 if (*s < '0' || *s > '9') {
283 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
286 plen = atoi(slash + 1);
287 if (plen < 0 || plen > 128) {
288 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
293 memset(&hints, 0, sizeof(hints));
294 hints.ai_socktype = conf->pdef->socktype;
295 hints.ai_family = AF_UNSPEC;
296 hints.ai_flags = ai_flags;
297 if (!conf->host && !conf->port) {
298 /* getaddrinfo() doesn't like host and port to be NULL */
299 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
300 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
303 for (res = addrinfo; res; res = res->ai_next)
304 port_set(res->ai_addr, 0);
307 hints.ai_flags |= AI_NUMERICHOST;
308 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
309 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
314 switch (addrinfo->ai_family) {
317 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
318 freeaddrinfo(addrinfo);
325 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
326 freeaddrinfo(addrinfo);
329 conf->prefixlen = plen;
331 conf->prefixlen = 255;
334 freeaddrinfo(conf->addrinfo);
335 conf->addrinfo = addrinfo;
339 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
344 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
348 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
350 debugx(1, DBG_ERR, "no ] matching initial [");
354 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
357 debugx(1, DBG_ERR, "missing host/address");
359 conf->host = stringcopy(field, p - field);
362 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
363 debugx(1, DBG_ERR, "unexpected character after ]");
366 /* port number or service name is specified */;
368 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
370 debugx(1, DBG_ERR, "syntax error, : but no following port");
371 conf->port = stringcopy(field, p - field);
373 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
377 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
378 struct clsrvconf *conf;
380 conf = malloc(sizeof(struct clsrvconf));
382 debugx(1, DBG_ERR, "malloc failed");
383 memset(conf, 0, sizeof(struct clsrvconf));
385 conf->pdef = &protodefs[conf->type];
387 parsehostport(lconf, conf, default_port);
388 if (!strcmp(conf->host, "*")) {
393 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
394 if (!resolvepeer(conf, AI_PASSIVE))
395 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
399 void freeclsrvres(struct clsrvconf *res) {
403 freeaddrinfo(res->addrinfo);
407 /* returns 1 if the len first bits are equal, else 0 */
408 int prefixmatch(void *a1, void *a2, uint8_t len) {
409 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
411 if (l && memcmp(a1, a2, l))
416 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
419 /* returns next config with matching address, or NULL */
420 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
421 struct sockaddr_in6 *sa6 = NULL;
422 struct in_addr *a4 = NULL;
423 struct addrinfo *res;
424 struct list_node *entry;
425 struct clsrvconf *conf;
427 if (addr->sa_family == AF_INET6) {
428 sa6 = (struct sockaddr_in6 *)addr;
429 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
430 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
434 a4 = &((struct sockaddr_in *)addr)->sin_addr;
436 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
437 conf = (struct clsrvconf *)entry->data;
438 if (conf->type == type) {
439 if (conf->prefixlen == 255) {
440 for (res = conf->addrinfo; res; res = res->ai_next)
441 if ((a4 && res->ai_family == AF_INET &&
442 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
443 (sa6 && res->ai_family == AF_INET6 &&
444 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
450 res = conf->addrinfo;
452 ((a4 && res->ai_family == AF_INET &&
453 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
454 (sa6 && res->ai_family == AF_INET6 &&
455 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
466 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
467 return find_conf(type, addr, clconfs, cur);
470 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
471 return find_conf(type, addr, srvconfs, cur);
474 /* returns next config of given type, or NULL */
475 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
476 struct list_node *entry;
477 struct clsrvconf *conf;
479 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
480 conf = (struct clsrvconf *)entry->data;
481 if (conf->type == type) {
490 struct queue *newqueue() {
493 q = malloc(sizeof(struct queue));
495 debugx(1, DBG_ERR, "malloc failed");
496 q->entries = list_create();
498 debugx(1, DBG_ERR, "malloc failed");
499 pthread_mutex_init(&q->mutex, NULL);
500 pthread_cond_init(&q->cond, NULL);
504 void removequeue(struct queue *q) {
505 struct list_node *entry;
509 pthread_mutex_lock(&q->mutex);
510 for (entry = list_first(q->entries); entry; entry = list_next(entry))
511 freerq((struct request *)entry);
512 list_destroy(q->entries);
513 pthread_cond_destroy(&q->cond);
514 pthread_mutex_unlock(&q->mutex);
515 pthread_mutex_destroy(&q->mutex);
519 void freebios(struct queue *q) {
522 pthread_mutex_lock(&q->mutex);
523 while ((bio = (BIO *)list_shift(q->entries)))
525 pthread_mutex_unlock(&q->mutex);
529 struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
530 struct client *new = malloc(sizeof(struct client));
533 debug(DBG_ERR, "malloc failed");
538 pthread_mutex_lock(conf->lock);
539 if (!conf->clients) {
540 conf->clients = list_create();
541 if (!conf->clients) {
543 pthread_mutex_unlock(conf->lock);
544 debug(DBG_ERR, "malloc failed");
549 memset(new, 0, sizeof(struct client));
551 if (conf->pdef->addclient)
552 conf->pdef->addclient(new);
554 new->replyq = newqueue();
555 list_push(conf->clients, new);
557 pthread_mutex_unlock(conf->lock);
561 void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
562 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
565 pthread_mutex_lock(&lock);
567 pthread_mutex_unlock(&lock);
570 void removeclientrqs(struct client *client) {
575 removeclientrqs_sendrq_freeserver_lock(1);
576 for (i = 0; i < MAX_REQUESTS; i++) {
581 rqout = rq->to->requests + rq->newid;
582 pthread_mutex_lock(rqout->lock);
583 if (rqout->rq == rq) /* still pointing to our request */
584 freerqoutdata(rqout);
585 pthread_mutex_unlock(rqout->lock);
589 removeclientrqs_sendrq_freeserver_lock(0);
592 void removelockedclient(struct client *client) {
593 struct clsrvconf *conf;
597 removeclientrqs(client);
598 removequeue(client->replyq);
599 list_removedata(conf->clients, client);
605 void removeclient(struct client *client) {
606 struct clsrvconf *conf;
612 pthread_mutex_lock(conf->lock);
613 removelockedclient(client);
614 pthread_mutex_unlock(conf->lock);
617 void freeserver(struct server *server, uint8_t destroymutex) {
618 struct rqout *rqout, *end;
623 removeclientrqs_sendrq_freeserver_lock(1);
624 if (server->requests) {
625 rqout = server->requests;
626 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
628 rqout->rq->to = NULL;
629 freerqoutdata(rqout);
630 pthread_mutex_destroy(rqout->lock);
633 free(server->requests);
636 freebios(server->rbios);
637 free(server->dynamiclookuparg);
639 SSL_free(server->ssl);
641 pthread_mutex_destroy(&server->lock);
642 pthread_cond_destroy(&server->newrq_cond);
643 pthread_mutex_destroy(&server->newrq_mutex);
645 removeclientrqs_sendrq_freeserver_lock(0);
649 int addserver(struct clsrvconf *conf) {
650 struct clsrvconf *res;
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 if (!srcprotores[type]) {
671 res = resolve_hostport(type, *conf->pdef->srcaddrport, NULL);
672 srcprotores[type] = res->addrinfo;
673 res->addrinfo = NULL;
677 conf->servers->sock = -1;
678 if (conf->pdef->addserverextra)
679 conf->pdef->addserverextra(conf);
681 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
682 if (!conf->servers->requests) {
683 debug(DBG_ERR, "malloc failed");
686 for (i = 0; i < MAX_REQUESTS; i++) {
687 conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
688 if (!conf->servers->requests[i].lock) {
689 debug(DBG_ERR, "malloc failed");
692 if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
693 debug(DBG_ERR, "mutex init failed");
694 free(conf->servers->requests[i].lock);
695 conf->servers->requests[i].lock = NULL;
699 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
700 debug(DBG_ERR, "mutex init failed");
703 conf->servers->newrq = 0;
704 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
705 debug(DBG_ERR, "mutex init failed");
706 pthread_mutex_destroy(&conf->servers->lock);
709 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
710 debug(DBG_ERR, "mutex init failed");
711 pthread_mutex_destroy(&conf->servers->newrq_mutex);
712 pthread_mutex_destroy(&conf->servers->lock);
719 freeserver(conf->servers, 0);
720 conf->servers = NULL;
724 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
725 int loc, i, l, n, r = 0;
728 STACK_OF(GENERAL_NAME) *alt;
731 debug(DBG_DBG, "subjectaltnameaddr");
733 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
737 ex = X509_get_ext(cert, loc);
738 alt = X509V3_EXT_d2i(ex);
742 n = sk_GENERAL_NAME_num(alt);
743 for (i = 0; i < n; i++) {
744 gn = sk_GENERAL_NAME_value(alt, i);
745 if (gn->type != GEN_IPADD)
748 v = (char *)ASN1_STRING_data(gn->d.ia5);
749 l = ASN1_STRING_length(gn->d.ia5);
750 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
751 && !memcmp(v, &addr, l)) {
756 GENERAL_NAMES_free(alt);
760 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
767 nm = X509_get_subject_name(cert);
770 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
773 e = X509_NAME_get_entry(nm, loc);
774 t = X509_NAME_ENTRY_get_data(e);
775 v = (char *) ASN1_STRING_data(t);
776 l = ASN1_STRING_length(t);
780 if (l == strlen(exact) && !strncasecmp(exact, v, l))
783 s = stringcopy((char *)v, l);
785 debug(DBG_ERR, "malloc failed");
788 if (regexec(regex, s, 0, NULL, 0)) {
799 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
800 int loc, i, l, n, r = 0;
803 STACK_OF(GENERAL_NAME) *alt;
806 debug(DBG_DBG, "subjectaltnameregexp");
808 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
812 ex = X509_get_ext(cert, loc);
813 alt = X509V3_EXT_d2i(ex);
817 n = sk_GENERAL_NAME_num(alt);
818 for (i = 0; i < n; i++) {
819 gn = sk_GENERAL_NAME_value(alt, i);
820 if (gn->type != type)
823 v = (char *)ASN1_STRING_data(gn->d.ia5);
824 l = ASN1_STRING_length(gn->d.ia5);
828 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
831 if (memcmp(v, exact, l))
834 s = stringcopy((char *)v, l);
836 debug(DBG_ERR, "malloc failed");
839 if (regexec(regex, s, 0, NULL, 0)) {
848 GENERAL_NAMES_free(alt);
852 X509 *verifytlscert(SSL *ssl) {
856 if (SSL_get_verify_result(ssl) != X509_V_OK) {
857 debug(DBG_ERR, "verifytlscert: basic validation failed");
858 while ((error = ERR_get_error()))
859 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
863 cert = SSL_get_peer_certificate(ssl);
865 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
869 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
871 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
872 struct in6_addr addr;
874 if (conf->certnamecheck && conf->prefixlen == 255) {
875 if (inet_pton(AF_INET, conf->host, &addr))
877 else if (inet_pton(AF_INET6, conf->host, &addr))
880 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
883 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
886 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
888 if (!cnregexp(cert, conf->host, NULL)) {
889 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
892 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
895 if (conf->certcnregex) {
896 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
897 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
900 debug(DBG_DBG, "verifyconfcert: CN matching regex");
902 if (conf->certuriregex) {
903 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
904 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
907 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
912 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
914 if (ATTRTYPE(attrs) == type)
916 length -= ATTRLEN(attrs);
917 attrs += ATTRLEN(attrs);
922 struct request *newrqref(struct request *rq) {
928 void freerq(struct request *rq) {
931 debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
934 if (rq->origusername)
935 free(rq->origusername);
941 radmsg_free(rq->msg);
945 void freerqoutdata(struct rqout *rqout) {
953 memset(&rqout->expiry, 0, sizeof(struct timeval));
956 void sendrq(struct request *rq) {
960 removeclientrqs_sendrq_freeserver_lock(1);
965 start = to->conf->statusserver ? 1 : 0;
966 pthread_mutex_lock(&to->newrq_mutex);
967 if (start && rq->msg->code == RAD_Status_Server) {
968 pthread_mutex_lock(to->requests[0].lock);
969 if (to->requests[0].rq) {
970 pthread_mutex_unlock(to->requests[0].lock);
971 debug(DBG_WARN, "sendrq: status server already in queue, dropping request");
978 /* might simplify if only try nextid, might be ok */
979 for (i = to->nextid; i < MAX_REQUESTS; i++) {
980 if (!to->requests[i].rq) {
981 pthread_mutex_lock(to->requests[i].lock);
982 if (!to->requests[i].rq)
984 pthread_mutex_unlock(to->requests[i].lock);
987 if (i == MAX_REQUESTS) {
988 for (i = start; i < to->nextid; i++) {
989 if (!to->requests[i].rq) {
990 pthread_mutex_lock(to->requests[i].lock);
991 if (!to->requests[i].rq)
993 pthread_mutex_unlock(to->requests[i].lock);
996 if (i == to->nextid) {
997 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
1002 rq->newid = (uint8_t)i;
1003 rq->msg->id = (uint8_t)i;
1004 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
1006 pthread_mutex_unlock(to->requests[i].lock);
1007 debug(DBG_ERR, "sendrq: radmsg2buf failed");
1011 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1012 to->requests[i].rq = rq;
1013 pthread_mutex_unlock(to->requests[i].lock);
1014 if (i >= start) /* i is not reserved for statusserver */
1019 debug(DBG_DBG, "sendrq: signalling client writer");
1020 pthread_cond_signal(&to->newrq_cond);
1023 pthread_mutex_unlock(&to->newrq_mutex);
1024 removeclientrqs_sendrq_freeserver_lock(0);
1029 rmclientrq(rq, rq->msg->id);
1031 pthread_mutex_unlock(&to->newrq_mutex);
1032 removeclientrqs_sendrq_freeserver_lock(0);
1035 void sendreply(struct request *rq) {
1037 struct client *to = rq->from;
1040 rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
1041 radmsg_free(rq->msg);
1043 if (!rq->replybuf) {
1045 debug(DBG_ERR, "sendreply: radmsg2buf failed");
1049 pthread_mutex_lock(&to->replyq->mutex);
1050 first = list_first(to->replyq->entries) == NULL;
1052 if (!list_push(to->replyq->entries, rq)) {
1053 pthread_mutex_unlock(&to->replyq->mutex);
1055 debug(DBG_ERR, "sendreply: malloc failed");
1060 debug(DBG_DBG, "signalling server writer");
1061 pthread_cond_signal(&to->replyq->cond);
1063 pthread_mutex_unlock(&to->replyq->mutex);
1066 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1067 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1068 static unsigned char first = 1;
1069 static EVP_MD_CTX mdctx;
1070 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1071 unsigned int md_len;
1072 uint8_t i, offset = 0, out[128];
1074 pthread_mutex_lock(&lock);
1076 EVP_MD_CTX_init(&mdctx);
1082 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1083 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1084 !EVP_DigestUpdate(&mdctx, input, 16) ||
1085 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1087 pthread_mutex_unlock(&lock);
1090 for (i = 0; i < 16; i++)
1091 out[offset + i] = hash[i] ^ in[offset + i];
1092 input = out + offset - 16;
1097 memcpy(in, out, len);
1098 pthread_mutex_unlock(&lock);
1102 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1103 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1104 static unsigned char first = 1;
1105 static EVP_MD_CTX mdctx;
1106 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1107 unsigned int md_len;
1108 uint8_t i, offset = 0, out[128];
1110 pthread_mutex_lock(&lock);
1112 EVP_MD_CTX_init(&mdctx);
1118 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1119 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1120 !EVP_DigestUpdate(&mdctx, input, 16) ||
1121 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1123 pthread_mutex_unlock(&lock);
1126 for (i = 0; i < 16; i++)
1127 out[offset + i] = hash[i] ^ in[offset + i];
1128 input = in + offset;
1133 memcpy(in, out, len);
1134 pthread_mutex_unlock(&lock);
1138 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1139 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1140 static unsigned char first = 1;
1141 static EVP_MD_CTX mdctx;
1142 unsigned char hash[EVP_MAX_MD_SIZE];
1143 unsigned int md_len;
1146 pthread_mutex_lock(&lock);
1148 EVP_MD_CTX_init(&mdctx);
1153 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1154 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1155 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1158 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1159 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1160 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1161 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1162 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1163 pthread_mutex_unlock(&lock);
1168 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1171 for (i = 0; i < 16; i++)
1174 for (offset = 16; offset < len; offset += 16) {
1176 printf("text + offset - 16 c(%d): ", offset / 16);
1177 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1179 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1180 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1181 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1182 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1184 pthread_mutex_unlock(&lock);
1188 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1191 for (i = 0; i < 16; i++)
1192 text[offset + i] ^= hash[i];
1196 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1199 pthread_mutex_unlock(&lock);
1203 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1204 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1205 static unsigned char first = 1;
1206 static EVP_MD_CTX mdctx;
1207 unsigned char hash[EVP_MAX_MD_SIZE];
1208 unsigned int md_len;
1212 pthread_mutex_lock(&lock);
1214 EVP_MD_CTX_init(&mdctx);
1219 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1220 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1221 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1224 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1225 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1226 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1227 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1228 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1229 pthread_mutex_unlock(&lock);
1234 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1237 for (i = 0; i < 16; i++)
1238 plain[i] = text[i] ^ hash[i];
1240 for (offset = 16; offset < len; offset += 16) {
1242 printf("text + offset - 16 c(%d): ", offset / 16);
1243 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1245 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1246 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1247 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1248 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1250 pthread_mutex_unlock(&lock);
1254 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1257 for (i = 0; i < 16; i++)
1258 plain[offset + i] = text[offset + i] ^ hash[i];
1261 memcpy(text, plain, len);
1263 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1266 pthread_mutex_unlock(&lock);
1270 struct realm *newrealmref(struct realm *r) {
1276 /* returns with lock on realm */
1277 struct realm *id2realm(struct list *realmlist, char *id) {
1278 struct list_node *entry;
1279 struct realm *realm, *subrealm;
1281 /* need to do locking for subrealms and check subrealm timers */
1282 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1283 realm = (struct realm *)entry->data;
1284 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1285 pthread_mutex_lock(&realm->mutex);
1286 if (realm->subrealms) {
1287 subrealm = id2realm(realm->subrealms, id);
1289 pthread_mutex_unlock(&realm->mutex);
1293 return newrealmref(realm);
1299 /* helper function, only used by removeserversubrealms() */
1300 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1301 struct list_node *entry, *entry2;
1302 struct realm *realm;
1304 for (entry = list_first(realmlist); entry;) {
1305 realm = newrealmref((struct realm *)entry->data);
1306 pthread_mutex_lock(&realm->mutex);
1307 entry = list_next(entry);
1309 if (realm->srvconfs) {
1310 for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
1311 if (entry2->data == srv)
1313 list_removedata(realm->srvconfs, srv);
1314 if (!list_first(realm->srvconfs)) {
1315 list_destroy(realm->srvconfs);
1316 realm->srvconfs = NULL;
1319 if (realm->accsrvconfs) {
1320 for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
1321 if (entry2->data == srv)
1323 list_removedata(realm->accsrvconfs, srv);
1324 if (!list_first(realm->accsrvconfs)) {
1325 list_destroy(realm->accsrvconfs);
1326 realm->accsrvconfs = NULL;
1330 /* remove subrealm if no servers */
1331 if (!realm->srvconfs && !realm->accsrvconfs)
1332 list_removedata(realmlist, realm);
1334 pthread_mutex_unlock(&realm->mutex);
1339 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1340 struct list_node *entry;
1341 struct realm *realm;
1343 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1344 realm = (struct realm *)entry->data;
1345 pthread_mutex_lock(&realm->mutex);
1346 if (realm->subrealms) {
1347 _internal_removeserversubrealms(realm->subrealms, srv);
1348 if (!list_first(realm->subrealms)) {
1349 list_destroy(realm->subrealms);
1350 realm->subrealms = NULL;
1353 pthread_mutex_unlock(&realm->mutex);
1357 int attrvalidate(unsigned char *attrs, int length) {
1358 while (length > 1) {
1359 if (ATTRLEN(attrs) < 2) {
1360 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1363 length -= ATTRLEN(attrs);
1365 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1368 attrs += ATTRLEN(attrs);
1371 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1375 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1376 if (len < 16 || len > 128 || len % 16) {
1377 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1381 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1382 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1386 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1388 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1389 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1395 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1398 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1399 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1402 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
1403 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1409 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1410 char *oldsecret, char *newsecret) {
1411 unsigned char *attr;
1413 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1414 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1415 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
1421 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1425 for (; attrs[0]; attrs += 2)
1426 if (attrs[0] == vendor && attrs[1] == subattr)
1431 /* returns 1 if entire element is to be removed, else 0 */
1432 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
1433 uint8_t alen, sublen;
1437 if (!removevendorattrs)
1440 memcpy(&vendor, attr->v, 4);
1441 vendor = ntohl(vendor);
1442 while (*removevendorattrs && *removevendorattrs != vendor)
1443 removevendorattrs += 2;
1444 if (!*removevendorattrs)
1447 if (findvendorsubattr(removevendorattrs, vendor, -1))
1448 return 1; /* remove entire vendor attribute */
1450 sublen = attr->l - 4;
1451 subattrs = attr->v + 4;
1453 if (!attrvalidate(subattrs, sublen)) {
1454 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1458 while (sublen > 1) {
1459 alen = ATTRLEN(subattrs);
1461 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1462 memmove(subattrs, subattrs + alen, sublen);
1470 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
1471 struct list_node *n, *p;
1475 n = list_first(msg->attrs);
1477 attr = (struct tlv *)n->data;
1478 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
1479 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
1480 list_removedata(msg->attrs, attr);
1482 n = p ? list_next(p) : list_first(msg->attrs);
1489 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
1490 struct list_node *n;
1493 for (n = list_first(addattrs); n; n = list_next(n)) {
1494 a = copytlv((struct tlv *)n->data);
1497 if (!radmsg_add(msg, a)) {
1505 int resizeattr(struct tlv *attr, uint8_t newlen) {
1508 if (newlen != attr->l) {
1509 newv = realloc(attr->v, newlen);
1518 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1519 size_t nmatch = 10, reslen = 0, start = 0;
1520 regmatch_t pmatch[10], *pfield;
1524 in = stringcopy((char *)attr->v, attr->l);
1528 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1533 out = modattr->replacement;
1535 for (i = start; out[i]; i++) {
1536 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1537 pfield = &pmatch[out[i + 1] - '0'];
1538 if (pfield->rm_so >= 0) {
1539 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1545 reslen += i - start;
1547 debug(DBG_WARN, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1552 if (!resizeattr(attr, reslen)) {
1559 for (i = start; out[i]; i++) {
1560 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1561 pfield = &pmatch[out[i + 1] - '0'];
1562 if (pfield->rm_so >= 0) {
1563 memcpy(attr->v + reslen, out + start, i - start);
1564 reslen += i - start;
1565 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1566 reslen += pfield->rm_eo - pfield->rm_so;
1573 memcpy(attr->v + reslen, out + start, i - start);
1577 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1578 struct list_node *n, *m;
1580 for (n = list_first(msg->attrs); n; n = list_next(n))
1581 for (m = list_first(modattrs); m; m = list_next(m))
1582 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1583 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1588 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1591 if (rewrite->removeattrs || rewrite->removevendorattrs)
1592 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1593 if (rewrite->addattrs && !dorewriteadd(msg, rewrite->addattrs))
1595 if (rewrite->modattrs && !dorewritemod(msg, rewrite->modattrs))
1600 int rewriteusername(struct request *rq, struct tlv *attr) {
1601 char *orig = (char *)tlv2str(attr);
1602 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1606 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1607 rq->origusername = (char *)orig;
1613 const char *radmsgtype2string(uint8_t code) {
1614 static const char *rad_msg_names[] = {
1615 "", "Access-Request", "Access-Accept", "Access-Reject",
1616 "Accounting-Request", "Accounting-Response", "", "",
1617 "", "", "", "Access-Challenge",
1618 "Status-Server", "Status-Client"
1620 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1623 void char2hex(char *h, unsigned char c) {
1624 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1625 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1626 h[0] = hexdigits[c / 16];
1627 h[1] = hexdigits[c % 16];
1631 uint8_t *radattr2ascii(struct tlv *attr) {
1639 for (i = 0; i < attr->l; i++)
1640 if (attr->v[i] < 32 || attr->v[i] > 126)
1643 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1650 for (i = 0; i < attr->l; i++)
1651 if (attr->v[i] < 32 || attr->v[i] > 126) {
1653 char2hex((char *)d, attr->v[i]);
1661 void acclog(struct radmsg *msg, char *host) {
1665 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1667 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1670 username = radattr2ascii(attr);
1672 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1677 void respond(struct request *rq, uint8_t code, char *message) {
1681 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1683 debug(DBG_ERR, "respond: malloc failed");
1686 if (message && *message) {
1687 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1688 if (!attr || !radmsg_add(msg, attr)) {
1691 debug(DBG_ERR, "respond: malloc failed");
1696 radmsg_free(rq->msg);
1698 debug(DBG_DBG, "respond: sending %s to %s", radmsgtype2string(msg->code), rq->from->conf->host);
1699 sendreply(newrqref(rq));
1702 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1703 struct list_node *entry;
1704 struct clsrvconf *server, *best = NULL, *first = NULL;
1706 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1707 server = (struct clsrvconf *)entry->data;
1708 if (!server->servers)
1712 if (!server->servers->connectionok)
1714 if (!server->servers->lostrqs)
1720 if (server->servers->lostrqs < best->servers->lostrqs)
1723 return best ? best : first;
1726 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1727 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1728 struct clsrvconf *srvconf;
1729 struct realm *subrealm;
1730 struct server *server = NULL;
1731 char *id = (char *)tlv2str(username);
1735 /* returns with lock on realm */
1736 *realm = id2realm(realms, id);
1739 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1740 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1743 server = srvconf->servers;
1744 if (!acc && !(*realm)->parent && !srvconf->servers) {
1745 subrealm = adddynamicrealmserver(*realm, srvconf, id);
1747 pthread_mutex_lock(&subrealm->mutex);
1748 pthread_mutex_unlock(&(*realm)->mutex);
1751 server = ((struct clsrvconf *)subrealm->srvconfs->first->data)->servers;
1760 struct request *newrequest() {
1763 rq = malloc(sizeof(struct request));
1765 debug(DBG_ERR, "newrequest: malloc failed");
1768 memset(rq, 0, sizeof(struct request));
1770 gettimeofday(&rq->created, NULL);
1774 int addclientrq(struct request *rq) {
1778 r = rq->from->rqs[rq->rqid];
1780 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1781 gettimeofday(&now, NULL);
1782 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1784 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1785 sendreply(newrqref(r));
1787 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1793 rq->from->rqs[rq->rqid] = newrqref(rq);
1797 void rmclientrq(struct request *rq, uint8_t id) {
1800 r = rq->from->rqs[id];
1803 rq->from->rqs[id] = NULL;
1807 /* returns 0 if validation/authentication fails, else 1 */
1808 int radsrv(struct request *rq) {
1809 struct radmsg *msg = NULL;
1811 uint8_t *userascii = NULL;
1812 struct realm *realm = NULL;
1813 struct server *to = NULL;
1814 struct client *from = rq->from;
1816 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1821 debug(DBG_WARN, "radsrv: message validation failed, ignoring packet");
1828 memcpy(rq->rqauth, msg->auth, 16);
1830 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1831 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1832 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1836 if (!addclientrq(rq))
1839 if (msg->code == RAD_Status_Server) {
1840 respond(rq, RAD_Access_Accept, NULL);
1844 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1846 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1849 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1851 if (msg->code == RAD_Accounting_Request) {
1852 acclog(msg, from->conf->host);
1853 respond(rq, RAD_Accounting_Response, NULL);
1855 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1859 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1860 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1864 userascii = radattr2ascii(attr);
1867 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1869 /* will return with lock on the realm */
1870 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1872 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1877 if (realm->message && msg->code == RAD_Access_Request) {
1878 debug(DBG_INFO, "radsrv: sending reject to %s for %s", from->conf->host, userascii);
1879 respond(rq, RAD_Access_Reject, realm->message);
1880 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1881 acclog(msg, from->conf->host);
1882 respond(rq, RAD_Accounting_Response, NULL);
1887 if (options.loopprevention && !strcmp(from->conf->name, to->conf->name)) {
1888 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
1889 from->conf->name, to->conf->name);
1893 if (msg->code == RAD_Accounting_Request)
1894 memset(msg->auth, 0, 16);
1895 else if (!RAND_bytes(msg->auth, 16)) {
1896 debug(DBG_WARN, "radsrv: failed to generate random auth");
1901 printfchars(NULL, "auth", "%02x ", auth, 16);
1904 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1906 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1907 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1911 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1913 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1914 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1918 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1924 pthread_mutex_unlock(&realm->mutex);
1929 rmclientrq(rq, msg->id);
1934 pthread_mutex_unlock(&realm->mutex);
1940 void replyh(struct server *server, unsigned char *buf) {
1941 struct client *from;
1942 struct rqout *rqout;
1944 unsigned char *subattrs;
1945 uint8_t *username, *stationid, *replymsg;
1946 struct radmsg *msg = NULL;
1948 struct list_node *node;
1950 server->connectionok = 1;
1951 server->lostrqs = 0;
1953 rqout = server->requests + buf[1];
1954 pthread_mutex_lock(rqout->lock);
1955 if (!rqout->tries) {
1958 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1962 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1966 debug(DBG_WARN, "replyh: message validation failed, ignoring packet");
1969 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1970 && msg->code != RAD_Accounting_Response) {
1971 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1974 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1976 gettimeofday(&server->lastrcv, NULL);
1978 if (rqout->rq->msg->code == RAD_Status_Server) {
1979 freerqoutdata(rqout);
1980 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
1984 gettimeofday(&server->lastreply, NULL);
1985 from = rqout->rq->from;
1987 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1988 debug(DBG_WARN, "replyh: rewritein failed");
1993 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1994 attr = (struct tlv *)node->data;
1995 if (attr->t != RAD_Attr_Vendor_Specific)
1999 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
2002 sublen = attr->l - 4;
2003 subattrs = attr->v + 4;
2004 if (!attrvalidate(subattrs, sublen) ||
2005 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2006 rqout->rq, server->conf->secret, from->conf->secret) ||
2007 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2008 rqout->rq, server->conf->secret, from->conf->secret))
2012 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2016 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
2017 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
2019 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
2020 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
2023 debug(DBG_INFO, "%s for user %s stationid %s from %s (%s)",
2024 radmsgtype2string(msg->code), username, stationid, server->conf->host, replymsg);
2027 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2028 radmsgtype2string(msg->code), username, stationid, server->conf->host);
2032 debug(DBG_INFO, "%s for user %s from %s (%s)",
2033 radmsgtype2string(msg->code), username, server->conf->host, replymsg);
2036 debug(DBG_INFO, "%s for user %s from %s",
2037 radmsgtype2string(msg->code), username, server->conf->host);
2043 msg->id = (char)rqout->rq->rqid;
2044 memcpy(msg->auth, rqout->rq->rqauth, 16);
2047 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2050 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
2051 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
2052 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2055 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
2058 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
2059 debug(DBG_WARN, "replyh: rewriteout failed");
2063 debug(DBG_INFO, "replyh: passing reply to client %s (%s)", from->conf->name, addr2string(from->addr));
2064 radmsg_free(rqout->rq->msg);
2065 rqout->rq->msg = msg;
2066 sendreply(newrqref(rqout->rq));
2067 freerqoutdata(rqout);
2068 pthread_mutex_unlock(rqout->lock);
2073 pthread_mutex_unlock(rqout->lock);
2077 struct request *createstatsrvrq() {
2084 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
2087 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
2090 if (!radmsg_add(rq->msg, attr)) {
2101 /* code for removing state not finished */
2102 void *clientwr(void *arg) {
2103 struct server *server = (struct server *)arg;
2104 struct rqout *rqout = NULL;
2105 pthread_t clientrdth;
2106 int i, dynconffail = 0;
2109 struct timeval now, laststatsrv;
2110 struct timespec timeout;
2111 struct request *statsrvrq;
2112 struct clsrvconf *conf;
2114 conf = server->conf;
2116 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2121 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2122 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2126 memset(&timeout, 0, sizeof(struct timespec));
2128 if (conf->statusserver) {
2129 gettimeofday(&server->lastrcv, NULL);
2130 gettimeofday(&laststatsrv, NULL);
2133 if (conf->pdef->connecter) {
2134 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2136 server->connectionok = 1;
2137 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
2138 debug(DBG_ERR, "clientwr: pthread_create failed");
2142 server->connectionok = 1;
2145 pthread_mutex_lock(&server->newrq_mutex);
2146 if (!server->newrq) {
2147 gettimeofday(&now, NULL);
2148 /* random 0-7 seconds */
2149 RAND_bytes(&rnd, 1);
2151 if (conf->statusserver) {
2152 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2153 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
2155 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
2156 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
2158 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2159 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2162 if (timeout.tv_sec > now.tv_sec)
2163 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2165 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2168 if (server->newrq) {
2169 debug(DBG_DBG, "clientwr: got new request");
2174 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2176 pthread_mutex_unlock(&server->newrq_mutex);
2178 for (i = 0; i < MAX_REQUESTS; i++) {
2179 if (server->clientrdgone) {
2180 pthread_join(clientrdth, NULL);
2184 for (; i < MAX_REQUESTS; i++) {
2185 rqout = server->requests + i;
2187 pthread_mutex_lock(rqout->lock);
2190 pthread_mutex_unlock(rqout->lock);
2194 if (i == MAX_REQUESTS)
2197 gettimeofday(&now, NULL);
2198 if (now.tv_sec < rqout->expiry.tv_sec) {
2199 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2200 timeout.tv_sec = rqout->expiry.tv_sec;
2201 pthread_mutex_unlock(rqout->lock);
2205 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2206 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2207 if (conf->statusserver) {
2208 if (*rqout->rq->buf == RAD_Status_Server) {
2209 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2210 if (server->lostrqs < 255)
2214 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2215 if (server->lostrqs < 255)
2218 freerqoutdata(rqout);
2219 pthread_mutex_unlock(rqout->lock);
2223 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2224 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2225 timeout.tv_sec = rqout->expiry.tv_sec;
2227 conf->pdef->clientradput(server, rqout->rq->buf);
2228 pthread_mutex_unlock(rqout->lock);
2230 if (conf->statusserver && server->connectionok) {
2231 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2232 gettimeofday(&now, NULL);
2233 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
2235 statsrvrq = createstatsrvrq();
2237 statsrvrq->to = server;
2238 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2245 conf->servers = NULL;
2246 if (server->dynamiclookuparg) {
2247 removeserversubrealms(realms, conf);
2251 freeclsrvconf(conf);
2253 freeserver(server, 1);
2254 ERR_remove_state(0);
2258 void createlistener(uint8_t type, char *arg) {
2260 struct clsrvconf *listenres;
2261 struct addrinfo *res;
2262 int s = -1, on = 1, *sp = NULL;
2264 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2266 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2268 for (res = listenres->addrinfo; res; res = res->ai_next) {
2269 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2271 debug(DBG_WARN, "createlistener: socket failed");
2274 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2276 if (res->ai_family == AF_INET6)
2277 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2279 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2280 debug(DBG_WARN, "createlistener: bind failed");
2286 sp = malloc(sizeof(int));
2288 debugx(1, DBG_ERR, "malloc failed");
2290 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
2291 debugx(1, DBG_ERR, "pthread_create failed");
2295 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2297 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
2298 listenres->host ? listenres->host : "*", listenres->port);
2299 freeclsrvres(listenres);
2302 void createlisteners(uint8_t type, char **args) {
2306 for (i = 0; args[i]; i++)
2307 createlistener(type, args[i]);
2309 createlistener(type, NULL);
2313 void ssl_info_callback(const SSL *ssl, int where, int ret) {
2317 w = where & ~SSL_ST_MASK;
2319 if (w & SSL_ST_CONNECT)
2321 else if (w & SSL_ST_ACCEPT)
2326 if (where & SSL_CB_LOOP)
2327 debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
2328 else if (where & SSL_CB_ALERT) {
2329 s = (where & SSL_CB_READ) ? "read" : "write";
2330 debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
2332 else if (where & SSL_CB_EXIT) {
2334 debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
2336 debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
2346 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2347 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2348 for (i = 0; i < CRYPTO_num_locks(); i++) {
2349 ssl_lock_count[i] = 0;
2350 pthread_mutex_init(&ssl_locks[i], NULL);
2352 CRYPTO_set_id_callback(ssl_thread_id);
2353 CRYPTO_set_locking_callback(ssl_locking_callback);
2355 SSL_load_error_strings();
2358 while (!RAND_status()) {
2361 RAND_seed((unsigned char *)&t, sizeof(time_t));
2362 RAND_seed((unsigned char *)&pid, sizeof(pid));
2366 X509_VERIFY_PARAM *createverifyparams(char **poids) {
2367 X509_VERIFY_PARAM *pm;
2368 ASN1_OBJECT *pobject;
2371 pm = X509_VERIFY_PARAM_new();
2375 for (i = 0; poids[i]; i++) {
2376 pobject = OBJ_txt2obj(poids[i], 0);
2378 X509_VERIFY_PARAM_free(pm);
2381 X509_VERIFY_PARAM_add0_policy(pm, pobject);
2384 X509_VERIFY_PARAM_set_flags(pm, X509_V_FLAG_POLICY_CHECK | X509_V_FLAG_EXPLICIT_POLICY);
2388 int tlsaddcacrl(SSL_CTX *ctx, struct tls *conf) {
2389 STACK_OF(X509_NAME) *calist;
2391 unsigned long error;
2393 if (!SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2394 while ((error = ERR_get_error()))
2395 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2396 debug(DBG_ERR, "tlsaddcacrl: Error updating TLS context %s", conf->name);
2400 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2401 if (!conf->cacertfile || calist) {
2402 if (conf->cacertpath) {
2404 calist = sk_X509_NAME_new_null();
2405 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2406 sk_X509_NAME_free(calist);
2412 while ((error = ERR_get_error()))
2413 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2414 debug(DBG_ERR, "tlsaddcacrl: Error adding CA subjects in TLS context %s", conf->name);
2417 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2418 SSL_CTX_set_client_CA_list(ctx, calist);
2420 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2421 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2423 if (conf->crlcheck || conf->vpm) {
2424 x509_s = SSL_CTX_get_cert_store(ctx);
2426 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2428 X509_STORE_set1_param(x509_s, conf->vpm);
2431 debug(DBG_DBG, "tlsaddcacrl: updated TLS context %s", conf->name);
2435 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2436 SSL_CTX *ctx = NULL;
2437 unsigned long error;
2444 ctx = SSL_CTX_new(TLSv1_method());
2446 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2450 ctx = SSL_CTX_new(DTLSv1_method());
2452 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2454 SSL_CTX_set_read_ahead(ctx, 1);
2458 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2462 if (conf->certkeypwd) {
2463 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2464 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2466 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2467 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2468 !SSL_CTX_check_private_key(ctx)) {
2469 while ((error = ERR_get_error()))
2470 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2471 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2476 if (conf->policyoids) {
2478 conf->vpm = createverifyparams(conf->policyoids);
2480 debug(DBG_ERR, "tlsaddcacrl: Failed to add policyOIDs in TLS context %s", conf->name);
2487 if (!tlsaddcacrl(ctx, conf)) {
2489 X509_VERIFY_PARAM_free(conf->vpm);
2496 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
2500 struct tls *tlsgettls(char *alt1, char *alt2) {
2503 t = hash_read(tlsconfs, alt1, strlen(alt1));
2505 t = hash_read(tlsconfs, alt2, strlen(alt2));
2509 SSL_CTX *tlsgetctx(uint8_t type, struct tls *t) {
2514 gettimeofday(&now, NULL);
2518 if (t->tlsexpiry && t->tlsctx) {
2519 if (t->tlsexpiry < now.tv_sec) {
2520 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
2521 tlsaddcacrl(t->tlsctx, t);
2525 t->tlsctx = tlscreatectx(RAD_TLS, t);
2527 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
2531 if (t->dtlsexpiry && t->dtlsctx) {
2532 if (t->dtlsexpiry < now.tv_sec) {
2533 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
2534 tlsaddcacrl(t->dtlsctx, t);
2538 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2540 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
2547 struct list *addsrvconfs(char *value, char **names) {
2548 struct list *conflist;
2550 struct list_node *entry;
2551 struct clsrvconf *conf = NULL;
2553 if (!names || !*names)
2556 conflist = list_create();
2558 debug(DBG_ERR, "malloc failed");
2562 for (n = 0; names[n]; n++) {
2563 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2564 conf = (struct clsrvconf *)entry->data;
2565 if (!strcasecmp(names[n], conf->name))
2569 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2570 list_destroy(conflist);
2573 if (!list_push(conflist, conf)) {
2574 debug(DBG_ERR, "malloc failed");
2575 list_destroy(conflist);
2578 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2583 void freerealm(struct realm *realm) {
2586 debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2587 if (--realm->refcount)
2591 free(realm->message);
2592 regfree(&realm->regex);
2593 pthread_mutex_destroy(&realm->mutex);
2594 /* if refcount == 0, all subrealms gone */
2595 list_destroy(realm->subrealms);
2596 /* if refcount == 0, all srvconfs gone */
2597 list_destroy(realm->srvconfs);
2598 /* if refcount == 0, all accsrvconfs gone */
2599 list_destroy(realm->accsrvconfs);
2600 freerealm(realm->parent);
2604 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2606 struct realm *realm;
2607 char *s, *regex = NULL;
2609 if (*value == '/') {
2610 /* regexp, remove optional trailing / if present */
2611 if (value[strlen(value) - 1] == '/')
2612 value[strlen(value) - 1] = '\0';
2614 /* not a regexp, let us make it one */
2615 if (*value == '*' && !value[1])
2616 regex = stringcopy(".*", 0);
2618 for (n = 0, s = value; *s;)
2621 regex = malloc(strlen(value) + n + 3);
2624 for (n = 1, s = value; *s; s++) {
2634 debug(DBG_ERR, "malloc failed");
2638 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2641 realm = malloc(sizeof(struct realm));
2643 debug(DBG_ERR, "malloc failed");
2646 memset(realm, 0, sizeof(struct realm));
2648 if (pthread_mutex_init(&realm->mutex, NULL)) {
2649 debug(DBG_ERR, "mutex init failed");
2655 realm->name = stringcopy(value, 0);
2657 debug(DBG_ERR, "malloc failed");
2660 if (message && strlen(message) > 253) {
2661 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2664 realm->message = message;
2665 realm->accresp = accresp;
2667 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2668 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2672 if (servers && *servers) {
2673 realm->srvconfs = addsrvconfs(value, servers);
2674 if (!realm->srvconfs)
2678 if (accservers && *accservers) {
2679 realm->accsrvconfs = addsrvconfs(value, accservers);
2680 if (!realm->accsrvconfs)
2684 if (!list_push(realmlist, realm)) {
2685 debug(DBG_ERR, "malloc failed");
2686 pthread_mutex_destroy(&realm->mutex);
2690 debug(DBG_DBG, "addrealm: added realm %s", value);
2694 while (list_shift(realm->srvconfs));
2695 while (list_shift(realm->accsrvconfs));
2702 for (n = 0; servers[n]; n++)
2704 freegconfmstr(servers);
2708 for (n = 0; accservers[n]; n++)
2710 freegconfmstr(accservers);
2712 return newrealmref(realm);
2715 struct realm *adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2716 struct clsrvconf *srvconf;
2717 struct realm *newrealm = NULL;
2718 char *realmname, *s;
2721 if (!conf->dynamiclookupcommand)
2724 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2725 realmname = strrchr(id, '@');
2731 for (s = realmname; *s; s++)
2732 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2735 srvconf = malloc(sizeof(struct clsrvconf));
2737 debug(DBG_ERR, "malloc failed");
2741 if (!addserver(srvconf))
2744 if (!realm->subrealms)
2745 realm->subrealms = list_create();
2746 if (!realm->subrealms)
2748 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2751 newrealm->parent = newrealmref(realm);
2753 /* add server and accserver to newrealm */
2754 newrealm->srvconfs = list_create();
2755 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2756 debug(DBG_ERR, "malloc failed");
2759 newrealmref(newrealm);
2760 newrealm->accsrvconfs = list_create();
2761 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2762 debug(DBG_ERR, "malloc failed");
2763 list_shift(realm->srvconfs);
2764 freerealm(newrealm);
2767 newrealmref(newrealm);
2769 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2770 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2771 debug(DBG_ERR, "pthread_create failed");
2772 list_shift(realm->srvconfs);
2773 freerealm(newrealm);
2774 list_shift(realm->accsrvconfs);
2775 freerealm(newrealm);
2778 pthread_detach(clientth);
2783 list_removedata(realm->subrealms, newrealm);
2784 freerealm(newrealm);
2785 if (!list_first(realm->subrealms)) {
2786 list_destroy(realm->subrealms);
2787 realm->subrealms = NULL;
2790 freeserver(srvconf->servers, 1);
2792 debug(DBG_ERR, "failed to create dynamic server");
2796 int dynamicconfig(struct server *server) {
2797 int ok, fd[2], status;
2799 struct clsrvconf *conf = server->conf;
2800 struct gconffile *cf = NULL;
2802 /* for now we only learn hostname/address */
2803 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2806 debug(DBG_ERR, "dynamicconfig: pipe error");
2811 debug(DBG_ERR, "dynamicconfig: fork error");
2815 } else if (pid == 0) {
2818 if (fd[1] != STDOUT_FILENO) {
2819 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2820 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2823 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2824 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2828 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2829 ok = getgenericconfig(&cf, NULL,
2830 "Server", CONF_CBK, confserver_cb, (void *)conf,
2835 if (waitpid(pid, &status, 0) < 0) {
2836 debug(DBG_ERR, "dynamicconfig: wait error");
2841 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2849 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2853 int addmatchcertattr(struct clsrvconf *conf) {
2857 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2858 r = &conf->certcnregex;
2859 v = conf->matchcertattr + 4;
2860 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2861 r = &conf->certuriregex;
2862 v = conf->matchcertattr + 20;
2867 /* regexp, remove optional trailing / if present */
2868 if (v[strlen(v) - 1] == '/')
2869 v[strlen(v) - 1] = '\0';
2873 *r = malloc(sizeof(regex_t));
2875 debug(DBG_ERR, "malloc failed");
2878 if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2881 debug(DBG_ERR, "failed to compile regular expression %s", v);
2887 /* should accept both names and numeric values, only numeric right now */
2888 uint8_t attrname2val(char *attrname) {
2891 val = atoi(attrname);
2892 return val > 0 && val < 256 ? val : 0;
2895 /* should accept both names and numeric values, only numeric right now */
2896 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2899 *vendor = atoi(attrname);
2900 s = strchr(attrname, ':');
2905 *type = atoi(s + 1);
2906 return *type >= 0 && *type < 256;
2909 /* should accept both names and numeric values, only numeric right now */
2910 struct tlv *extractattr(char *nameval) {
2915 s = strchr(nameval, ':');
2916 name = atoi(nameval);
2917 if (!s || name < 1 || name > 255)
2919 len = strlen(s + 1);
2922 a = malloc(sizeof(struct tlv));
2925 a->v = (uint8_t *)stringcopy(s + 1, 0);
2935 /* should accept both names and numeric values, only numeric right now */
2936 struct modattr *extractmodattr(char *nameval) {
2941 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2945 s = strchr(nameval, ':');
2946 name = atoi(nameval);
2947 if (!s || name < 1 || name > 255 || s[1] != '/')
2951 /* regexp, remove optional trailing / if present */
2952 if (s[strlen(s) - 1] == '/')
2953 s[strlen(s) - 1] = '\0';
2961 m = malloc(sizeof(struct modattr));
2963 debug(DBG_ERR, "malloc failed");
2968 m->replacement = stringcopy(t, 0);
2969 if (!m->replacement) {
2971 debug(DBG_ERR, "malloc failed");
2975 m->regex = malloc(sizeof(regex_t));
2977 free(m->replacement);
2979 debug(DBG_ERR, "malloc failed");
2983 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2985 free(m->replacement);
2987 debug(DBG_ERR, "failed to compile regular expression %s", s);
2994 struct rewrite *getrewrite(char *alt1, char *alt2) {
2997 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2999 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
3004 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
3005 struct rewrite *rewrite = NULL;
3007 uint8_t *rma = NULL;
3008 uint32_t *p, *rmva = NULL;
3009 struct list *adda = NULL, *moda = NULL;
3014 for (n = 0; rmattrs[n]; n++);
3015 rma = calloc(n + 1, sizeof(uint8_t));
3017 debugx(1, DBG_ERR, "malloc failed");
3019 for (i = 0; i < n; i++)
3020 if (!(rma[i] = attrname2val(rmattrs[i])))
3021 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
3022 freegconfmstr(rmattrs);
3027 for (n = 0; rmvattrs[n]; n++);
3028 rmva = calloc(2 * n + 1, sizeof(uint32_t));
3030 debugx(1, DBG_ERR, "malloc failed");
3032 for (p = rmva, i = 0; i < n; i++, p += 2)
3033 if (!vattrname2val(rmvattrs[i], p, p + 1))
3034 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
3035 freegconfmstr(rmvattrs);
3040 adda = list_create();
3042 debugx(1, DBG_ERR, "malloc failed");
3043 for (i = 0; addattrs[i]; i++) {
3044 a = extractattr(addattrs[i]);
3046 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
3047 if (!list_push(adda, a))
3048 debugx(1, DBG_ERR, "malloc failed");
3050 freegconfmstr(addattrs);
3054 moda = list_create();
3056 debugx(1, DBG_ERR, "malloc failed");
3057 for (i = 0; modattrs[i]; i++) {
3058 m = extractmodattr(modattrs[i]);
3060 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
3061 if (!list_push(moda, m))
3062 debugx(1, DBG_ERR, "malloc failed");
3064 freegconfmstr(modattrs);
3067 if (rma || rmva || adda || moda) {
3068 rewrite = malloc(sizeof(struct rewrite));
3070 debugx(1, DBG_ERR, "malloc failed");
3071 rewrite->removeattrs = rma;
3072 rewrite->removevendorattrs = rmva;
3073 rewrite->addattrs = adda;
3074 rewrite->modattrs = moda;
3077 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
3078 debugx(1, DBG_ERR, "malloc failed");
3079 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3082 void freeclsrvconf(struct clsrvconf *conf) {
3088 free(conf->matchcertattr);
3089 if (conf->certcnregex)
3090 regfree(conf->certcnregex);
3091 if (conf->certuriregex)
3092 regfree(conf->certuriregex);
3093 free(conf->confrewritein);
3094 free(conf->confrewriteout);
3095 if (conf->rewriteusername) {
3096 if (conf->rewriteusername->regex)
3097 regfree(conf->rewriteusername->regex);
3098 free(conf->rewriteusername->replacement);
3099 free(conf->rewriteusername);
3101 free(conf->dynamiclookupcommand);
3102 free(conf->rewritein);
3103 free(conf->rewriteout);
3105 freeaddrinfo(conf->addrinfo);
3107 pthread_mutex_destroy(conf->lock);
3110 /* not touching ssl_ctx, clients and servers */
3114 int mergeconfstring(char **dst, char **src) {
3123 t = stringcopy(*dst, 0);
3125 debug(DBG_ERR, "malloc failed");
3133 /* assumes dst is a shallow copy */
3134 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3135 if (!mergeconfstring(&dst->name, &src->name) ||
3136 !mergeconfstring(&dst->host, &src->host) ||
3137 !mergeconfstring(&dst->port, &src->port) ||
3138 !mergeconfstring(&dst->secret, &src->secret) ||
3139 !mergeconfstring(&dst->tls, &src->tls) ||
3140 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3141 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
3142 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
3143 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3146 dst->pdef = src->pdef;
3147 dst->statusserver = src->statusserver;
3148 dst->certnamecheck = src->certnamecheck;
3149 if (src->retryinterval != 255)
3150 dst->retryinterval = src->retryinterval;
3151 if (src->retrycount != 255)
3152 dst->retrycount = src->retrycount;
3156 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3157 struct clsrvconf *conf;
3158 char *conftype = NULL, *rewriteinalias = NULL;
3159 long int dupinterval = LONG_MIN;
3161 debug(DBG_DBG, "confclient_cb called for %s", block);
3163 conf = malloc(sizeof(struct clsrvconf));
3165 debugx(1, DBG_ERR, "malloc failed");
3166 memset(conf, 0, sizeof(struct clsrvconf));
3167 conf->certnamecheck = 1;
3169 if (!getgenericconfig(cf, block,
3170 "type", CONF_STR, &conftype,
3171 "host", CONF_STR, &conf->host,
3172 "secret", CONF_STR, &conf->secret,
3173 "tls", CONF_STR, &conf->tls,
3174 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3175 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3176 "DuplicateInterval", CONF_LINT, &dupinterval,
3177 "rewrite", CONF_STR, &rewriteinalias,
3178 "rewriteIn", CONF_STR, &conf->confrewritein,
3179 "rewriteOut", CONF_STR, &conf->confrewriteout,
3180 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
3183 debugx(1, DBG_ERR, "configuration error");
3185 conf->name = stringcopy(val, 0);
3187 conf->host = stringcopy(val, 0);
3188 if (!conf->name || !conf->host)
3189 debugx(1, DBG_ERR, "malloc failed");
3192 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3193 conf->type = protoname2int(conftype);
3194 conf->pdef = &protodefs[conf->type];
3195 if (!conf->pdef->name)
3196 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3199 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3200 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
3202 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3203 if (conf->matchcertattr && !addmatchcertattr(conf))
3204 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3207 if (dupinterval != LONG_MIN) {
3208 if (dupinterval < 0 || dupinterval > 255)
3209 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
3210 conf->dupinterval = (uint8_t)dupinterval;
3212 conf->dupinterval = conf->pdef->duplicateintervaldefault;
3214 if (!conf->confrewritein)
3215 conf->confrewritein = rewriteinalias;
3217 free(rewriteinalias);
3218 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
3219 if (conf->confrewriteout)
3220 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3222 if (conf->confrewriteusername) {
3223 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
3224 if (!conf->rewriteusername)
3225 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3228 if (!resolvepeer(conf, 0))
3229 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3231 if (!conf->secret) {
3232 if (!conf->pdef->secretdefault)
3233 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3234 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3236 debugx(1, DBG_ERR, "malloc failed");
3239 conf->lock = malloc(sizeof(pthread_mutex_t));
3241 debugx(1, DBG_ERR, "malloc failed");
3243 pthread_mutex_init(conf->lock, NULL);
3244 if (!list_push(clconfs, conf))
3245 debugx(1, DBG_ERR, "malloc failed");
3249 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3250 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3251 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
3252 if (!conf->tlsconf) {
3253 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3256 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3257 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3263 conf->port = stringcopy(conf->pdef->portdefault, 0);
3265 debug(DBG_ERR, "malloc failed");
3270 if (conf->retryinterval == 255)
3271 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3272 if (conf->retrycount == 255)
3273 conf->retrycount = protodefs[conf->type].retrycountdefault;
3275 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
3276 if (conf->confrewriteout)
3277 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3279 if (!conf->secret) {
3280 if (!conf->pdef->secretdefault) {
3281 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3284 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3285 if (!conf->secret) {
3286 debug(DBG_ERR, "malloc failed");
3291 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3292 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3298 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3299 struct clsrvconf *conf, *resconf;
3300 char *conftype = NULL, *rewriteinalias = NULL;
3301 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3303 debug(DBG_DBG, "confserver_cb called for %s", block);
3305 conf = malloc(sizeof(struct clsrvconf));
3307 debug(DBG_ERR, "malloc failed");
3310 memset(conf, 0, sizeof(struct clsrvconf));
3311 resconf = (struct clsrvconf *)arg;
3313 conf->statusserver = resconf->statusserver;
3314 conf->certnamecheck = resconf->certnamecheck;
3316 conf->certnamecheck = 1;
3318 if (!getgenericconfig(cf, block,
3319 "type", CONF_STR, &conftype,
3320 "host", CONF_STR, &conf->host,
3321 "port", CONF_STR, &conf->port,
3322 "secret", CONF_STR, &conf->secret,
3323 "tls", CONF_STR, &conf->tls,
3324 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3325 "rewrite", CONF_STR, &rewriteinalias,
3326 "rewriteIn", CONF_STR, &conf->confrewritein,
3327 "rewriteOut", CONF_STR, &conf->confrewriteout,
3328 "StatusServer", CONF_BLN, &conf->statusserver,
3329 "RetryInterval", CONF_LINT, &retryinterval,
3330 "RetryCount", CONF_LINT, &retrycount,
3331 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3332 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3335 debug(DBG_ERR, "configuration error");
3339 conf->name = stringcopy(val, 0);
3341 debug(DBG_ERR, "malloc failed");
3345 conf->host = stringcopy(val, 0);
3347 debug(DBG_ERR, "malloc failed");
3353 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3354 conf->type = protoname2int(conftype);
3355 conf->pdef = &protodefs[conf->type];
3356 if (!conf->pdef->name) {
3357 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3363 if (!conf->confrewritein)
3364 conf->confrewritein = rewriteinalias;
3366 free(rewriteinalias);
3367 rewriteinalias = NULL;
3369 if (retryinterval != LONG_MIN) {
3370 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3371 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3374 conf->retryinterval = (uint8_t)retryinterval;
3376 conf->retryinterval = 255;
3378 if (retrycount != LONG_MIN) {
3379 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3380 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3383 conf->retrycount = (uint8_t)retrycount;
3385 conf->retrycount = 255;
3388 if (!mergesrvconf(resconf, conf))
3392 if (conf->dynamiclookupcommand) {
3393 free(conf->dynamiclookupcommand);
3394 conf->dynamiclookupcommand = NULL;
3398 if (resconf || !conf->dynamiclookupcommand) {
3399 if (!compileserverconfig(conf, block))
3406 if (!list_push(srvconfs, conf)) {
3407 debug(DBG_ERR, "malloc failed");
3414 free(rewriteinalias);
3415 freeclsrvconf(conf);
3419 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3420 char **servers = NULL, **accservers = NULL, *msg = NULL;
3421 uint8_t accresp = 0;
3423 debug(DBG_DBG, "confrealm_cb called for %s", block);
3425 if (!getgenericconfig(cf, block,
3426 "server", CONF_MSTR, &servers,
3427 "accountingServer", CONF_MSTR, &accservers,
3428 "ReplyMessage", CONF_STR, &msg,
3429 "AccountingResponse", CONF_BLN, &accresp,
3432 debugx(1, DBG_ERR, "configuration error");
3434 addrealm(realms, val, servers, accservers, msg, accresp);
3438 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3440 long int expiry = LONG_MIN;
3442 debug(DBG_DBG, "conftls_cb called for %s", block);
3444 conf = malloc(sizeof(struct tls));
3446 debug(DBG_ERR, "conftls_cb: malloc failed");
3449 memset(conf, 0, sizeof(struct tls));
3451 if (!getgenericconfig(cf, block,
3452 "CACertificateFile", CONF_STR, &conf->cacertfile,
3453 "CACertificatePath", CONF_STR, &conf->cacertpath,
3454 "CertificateFile", CONF_STR, &conf->certfile,
3455 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3456 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3457 "CacheExpiry", CONF_LINT, &expiry,
3458 "CRLCheck", CONF_BLN, &conf->crlcheck,
3459 "PolicyOID", CONF_MSTR, &conf->policyoids,
3462 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3465 if (!conf->certfile || !conf->certkeyfile) {
3466 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3469 if (!conf->cacertfile && !conf->cacertpath) {
3470 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3473 if (expiry != LONG_MIN) {
3475 debug(DBG_ERR, "error in block %s, value of option CacheExpiry is %ld, may not be negative", val, expiry);
3478 conf->cacheexpiry = expiry;
3481 conf->name = stringcopy(val, 0);
3483 debug(DBG_ERR, "conftls_cb: malloc failed");
3487 if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
3488 debug(DBG_ERR, "conftls_cb: malloc failed");
3491 if (!tlsgetctx(RAD_TLS, conf))
3492 debug(DBG_ERR, "conftls_cb: error creating ctx for TLS block %s", val);
3493 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3497 free(conf->cacertfile);
3498 free(conf->cacertpath);
3499 free(conf->certfile);
3500 free(conf->certkeyfile);
3501 free(conf->certkeypwd);
3502 freegconfmstr(conf->policyoids);
3507 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3508 char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3510 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3512 if (!getgenericconfig(cf, block,
3513 "removeAttribute", CONF_MSTR, &rmattrs,
3514 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3515 "addAttribute", CONF_MSTR, &addattrs,
3516 "modifyAttribute", CONF_MSTR, &modattrs,
3519 debugx(1, DBG_ERR, "configuration error");
3520 addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3524 void getmainconfig(const char *configfile) {
3525 long int loglevel = LONG_MIN;
3526 struct gconffile *cfs;
3528 cfs = openconfigfile(configfile);
3529 memset(&options, 0, sizeof(options));
3531 clconfs = list_create();
3533 debugx(1, DBG_ERR, "malloc failed");
3535 srvconfs = list_create();
3537 debugx(1, DBG_ERR, "malloc failed");
3539 realms = list_create();
3541 debugx(1, DBG_ERR, "malloc failed");
3543 tlsconfs = hash_create();
3545 debugx(1, DBG_ERR, "malloc failed");
3547 rewriteconfs = hash_create();
3549 debugx(1, DBG_ERR, "malloc failed");
3551 if (!getgenericconfig(&cfs, NULL,
3552 "ListenUDP", CONF_MSTR, &options.listenargs[RAD_UDP],
3553 "ListenTCP", CONF_MSTR, &options.listenargs[RAD_TCP],
3554 "ListenTLS", CONF_MSTR, &options.listenargs[RAD_TLS],
3555 "ListenDTLS", CONF_MSTR, &options.listenargs[RAD_DTLS],
3556 "SourceUDP", CONF_STR, &options.sourceudp,
3557 "SourceTCP", CONF_STR, &options.sourcetcp,
3558 "SourceTLS", CONF_STR, &options.sourcetls,
3559 "SourceDTLS", CONF_STR, &options.sourcedtls,
3560 "LogLevel", CONF_LINT, &loglevel,
3561 "LogDestination", CONF_STR, &options.logdestination,
3562 "LoopPrevention", CONF_BLN, &options.loopprevention,
3563 "Client", CONF_CBK, confclient_cb, NULL,
3564 "Server", CONF_CBK, confserver_cb, NULL,
3565 "Realm", CONF_CBK, confrealm_cb, NULL,
3566 "TLS", CONF_CBK, conftls_cb, NULL,
3567 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3570 debugx(1, DBG_ERR, "configuration error");
3572 if (loglevel != LONG_MIN) {
3573 if (loglevel < 1 || loglevel > 4)
3574 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3575 options.loglevel = (uint8_t)loglevel;
3579 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3582 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3585 *configfile = optarg;
3588 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3589 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3590 *loglevel = *optarg - '0';
3599 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3604 if (!(argc - optind))
3608 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3612 int daemon(int a, int b) {
3620 for (i = 0; i < 3; i++) {
3622 open("/dev/null", O_RDWR);
3628 void *sighandler(void *arg) {
3633 sigemptyset(&sigset);
3634 sigaddset(&sigset, SIGPIPE);
3635 sigwait(&sigset, &sig);
3636 /* only get SIGPIPE right now, so could simplify below code */
3639 /* completely ignoring this */
3642 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3645 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3650 int main(int argc, char **argv) {
3653 struct list_node *entry;
3654 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3655 char *configfile = NULL;
3656 struct clsrvconf *srvconf;
3659 debug_init("radsecproxy");
3660 debug_set_level(DEBUG_LEVEL);
3662 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3664 debug_set_level(loglevel);
3665 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3667 options.loglevel = loglevel;
3668 else if (options.loglevel)
3669 debug_set_level(options.loglevel);
3671 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3672 free(options.logdestination);
3674 if (!list_first(clconfs))
3675 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3676 if (!list_first(realms))
3677 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3680 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3682 if (!foreground && (daemon(0, 0) < 0))
3683 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3685 debug_timestamp_on();
3686 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3688 sigemptyset(&sigset);
3689 /* exit on all but SIGPIPE, ignore more? */
3690 sigaddset(&sigset, SIGPIPE);
3691 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3692 pthread_create(&sigth, NULL, sighandler, NULL);
3694 memset(srcprotores, 0, sizeof(srcprotores));
3695 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3696 srvconf = (struct clsrvconf *)entry->data;
3697 if (srvconf->dynamiclookupcommand)
3699 if (!addserver(srvconf))
3700 debugx(1, DBG_ERR, "failed to add server");
3701 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3702 (void *)(srvconf->servers)))
3703 debugx(1, DBG_ERR, "pthread_create failed");
3706 for (i = 0; protodefs[i].name; i++) {
3707 if (protodefs[i].freesrcprotores && srcprotores[i]) {
3708 freeaddrinfo(srcprotores[i]);
3709 srcprotores[i] = NULL;
3711 if (protodefs[i].initextra)
3712 protodefs[i].initextra();
3713 if (find_clconf_type(i, NULL))
3714 createlisteners(i, options.listenargs[i]);
3717 /* just hang around doing nothing, anything to do here? */