8f76aaa03379641f26ac029de59ddc48bb4b0598
[radsecproxy.git] / radsecproxy.c
1 /*
2  * Copyright (C) 2006-2008 Stig Venaas <venaas@uninett.no>
3  *
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.
7  */
8
9 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
10  *              rd is responsible for init and launching wr
11  * For TLS there is a server instance that launches tlsserverrd for each TLS peer
12  *          each tlsserverrd launches tlsserverwr
13  * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
14  *          for init and launching rd
15  *
16  * serverrd will receive a request, processes it and puts it in the requestq of
17  *          the appropriate clientwr
18  * clientwr monitors its requestq and sends requests
19  * clientrd looks for responses, processes them and puts them in the replyq of
20  *          the peer the request came from
21  * serverwr monitors its reply and sends replies
22  *
23  * In addition to the main thread, we have:
24  * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
25  * If TLS peers are configured, there will initially be 2 * #peers TLS threads
26  * For each TLS peer connecting to us there will be 2 more TLS threads
27  *       This is only for connected peers
28  * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
29  *          1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
30 */
31
32 /* Bugs:
33  * TCP accounting not yet supported
34  * We are not removing client requests from dynamic servers, see removeclientrqs()
35  */
36
37 #include <signal.h>
38 #include <sys/socket.h>
39 #include <netinet/in.h>
40 #include <netdb.h>
41 #include <string.h>
42 #include <unistd.h>
43 #include <limits.h>
44 #ifdef SYS_SOLARIS9
45 #include <fcntl.h>
46 #endif
47 #include <sys/time.h>
48 #include <sys/types.h>
49 #include <sys/select.h>
50 #include <ctype.h>
51 #include <sys/wait.h>
52 #include <arpa/inet.h>
53 #include <regex.h>
54 #include <libgen.h>
55 #include <pthread.h>
56 #include <openssl/ssl.h>
57 #include <openssl/rand.h>
58 #include <openssl/err.h>
59 #include <openssl/md5.h>
60 #include <openssl/hmac.h>
61 #include <openssl/x509v3.h>
62 #include "debug.h"
63 #include "list.h"
64 #include "util.h"
65 #include "gconfig.h"
66 #include "radsecproxy.h"
67 #include "udp.h"
68 #include "tcp.h"
69 #include "tls.h"
70 #include "dtls.h"
71
72 static struct options options;
73 static struct list *clconfs, *srvconfs;
74 struct list *realms, *tlsconfs, *rewriteconfs;
75
76 static struct addrinfo *srcprotores[4] = { NULL, NULL, NULL, NULL };
77
78 static pthread_mutex_t tlsconfs_lock;
79 static pthread_mutex_t *ssl_locks = NULL;
80 static long *ssl_lock_count;
81 extern int optind;
82 extern char *optarg;
83
84 /* minimum required declarations to avoid reordering code */
85 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
86 int dynamicconfig(struct server *server);
87 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
88 void freerealm(struct realm *realm);
89 void freeclsrvconf(struct clsrvconf *conf);
90 void freerqdata(struct request *rq);
91
92 static const struct protodefs protodefs[] = {
93     {   "udp", /* UDP, assuming RAD_UDP defined as 0 */
94         NULL, /* secretdefault */
95         SOCK_DGRAM, /* socktype */
96         "1812", /* portdefault */
97         REQUEST_RETRY_COUNT, /* retrycountdefault */
98         10, /* retrycountmax */
99         REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
100         60, /* retryintervalmax */
101         udpserverrd, /* listener */
102         &options.sourceudp, /* srcaddrport */
103         NULL, /* connecter */
104         NULL, /* clientconnreader */
105         clientradputudp, /* clientradput */
106         addclientudp, /* addclient */
107         addserverextraudp, /* addserverextra */
108         initextraudp /* initextra */
109     },
110     {   "tls", /* TLS, assuming RAD_TLS defined as 1 */
111         "mysecret", /* secretdefault */
112         SOCK_STREAM, /* socktype */
113         "2083", /* portdefault */
114         0, /* retrycountdefault */
115         0, /* retrycountmax */
116         REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
117         60, /* retryintervalmax */
118         tlslistener, /* listener */
119         &options.sourcetls, /* srcaddrport */
120         tlsconnect, /* connecter */
121         tlsclientrd, /* clientconnreader */
122         clientradputtls, /* clientradput */
123         NULL, /* addclient */
124         NULL, /* addserverextra */
125         NULL /* initextra */
126     },
127     {   "tcp", /* TCP, assuming RAD_TCP defined as 2 */
128         NULL, /* secretdefault */
129         SOCK_STREAM, /* socktype */
130         "1812", /* portdefault */
131         0, /* retrycountdefault */
132         0, /* retrycountmax */
133         REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
134         60, /* retryintervalmax */
135         tcplistener, /* listener */
136         &options.sourcetcp, /* srcaddrport */
137         tcpconnect, /* connecter */
138         tcpclientrd, /* clientconnreader */
139         clientradputtcp, /* clientradput */
140         NULL, /* addclient */
141         NULL, /* addserverextra */
142         NULL /* initextra */
143     },
144     {   "dtls", /* DTLS, assuming RAD_DTLS defined as 3 */
145         "mysecret", /* secretdefault */
146         SOCK_DGRAM, /* socktype */
147         "2083", /* portdefault */
148         REQUEST_RETRY_COUNT, /* retrycountdefault */
149         10, /* retrycountmax */
150         REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
151         60, /* retryintervalmax */
152         udpdtlsserverrd, /* listener */
153         &options.sourcedtls, /* srcaddrport */
154         dtlsconnect, /* connecter */
155         dtlsclientrd, /* clientconnreader */
156         clientradputdtls, /* clientradput */
157         addclientdtls, /* addclient */
158         addserverextradtls, /* addserverextra */
159         initextradtls /* initextra */
160     },
161     {   NULL
162     }
163 };
164
165 uint8_t protoname2int(const char *name) {
166     int i;
167
168     for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
169     return i;
170 }
171     
172 /* callbacks for making OpenSSL thread safe */
173 unsigned long ssl_thread_id() {
174         return (unsigned long)pthread_self();
175 }
176
177 void ssl_locking_callback(int mode, int type, const char *file, int line) {
178     if (mode & CRYPTO_LOCK) {
179         pthread_mutex_lock(&ssl_locks[type]);
180         ssl_lock_count[type]++;
181     } else
182         pthread_mutex_unlock(&ssl_locks[type]);
183 }
184
185 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
186     int pwdlen = strlen(userdata);
187     if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
188         return 0;
189     memcpy(buf, userdata, pwdlen);
190     return pwdlen;
191 }
192
193 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
194   char buf[256];
195   X509 *err_cert;
196   int err, depth;
197
198   err_cert = X509_STORE_CTX_get_current_cert(ctx);
199   err = X509_STORE_CTX_get_error(ctx);
200   depth = X509_STORE_CTX_get_error_depth(ctx);
201
202   if (depth > MAX_CERT_DEPTH) {
203       ok = 0;
204       err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
205       X509_STORE_CTX_set_error(ctx, err);
206   }
207
208   if (!ok) {
209       X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
210       debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
211
212       switch (err) {
213       case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
214           X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
215           debug(DBG_WARN, "\tIssuer=%s", buf);
216           break;
217       case X509_V_ERR_CERT_NOT_YET_VALID:
218       case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
219           debug(DBG_WARN, "\tCertificate not yet valid");
220           break;
221       case X509_V_ERR_CERT_HAS_EXPIRED:
222           debug(DBG_WARN, "Certificate has expired");
223           break;
224       case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
225           debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
226           break;
227       }
228   }
229 #ifdef DEBUG  
230   printf("certificate verify returns %d\n", ok);
231 #endif  
232   return ok;
233 }
234
235 struct addrinfo *getsrcprotores(uint8_t type) {
236     return srcprotores[type];
237 }
238
239 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
240     struct addrinfo hints, *addrinfo, *res;
241     char *slash, *s;
242     int plen = 0;
243
244     slash = conf->host ? strchr(conf->host, '/') : NULL;
245     if (slash) {
246         s = slash + 1;
247         if (!*s) {
248             debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
249             return 0;
250         }
251         for (; *s; s++)
252             if (*s < '0' || *s > '9') {
253                 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
254                 return 0;
255             }
256         plen = atoi(slash + 1);
257         if (plen < 0 || plen > 128) {
258             debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
259             return 0;
260         }
261         *slash = '\0';
262     }
263     memset(&hints, 0, sizeof(hints));
264     hints.ai_socktype = conf->pdef->socktype;
265     hints.ai_family = AF_UNSPEC;
266     hints.ai_flags = ai_flags;
267     if (!conf->host && !conf->port) {
268         /* getaddrinfo() doesn't like host and port to be NULL */
269         if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
270             debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
271             return 0;
272         }
273         for (res = addrinfo; res; res = res->ai_next) {
274             switch (res->ai_family) {
275             case AF_INET:
276                 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
277                 break;
278             case AF_INET6:
279                 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
280                 break;
281             }
282         }
283     } else {
284         if (slash)
285             hints.ai_flags |= AI_NUMERICHOST;
286         if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
287             debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
288             return 0;
289         }
290         if (slash) {
291             *slash = '/';
292             switch (addrinfo->ai_family) {
293             case AF_INET:
294                 if (plen > 32) {
295                     debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
296                     freeaddrinfo(addrinfo);
297                     return 0;
298                 }
299                 break;
300             case AF_INET6:
301                 break;
302             default:
303                 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
304                 freeaddrinfo(addrinfo);
305                 return 0;
306             }
307             conf->prefixlen = plen;
308         } else
309             conf->prefixlen = 255;
310     }
311     if (conf->addrinfo)
312         freeaddrinfo(conf->addrinfo);
313     conf->addrinfo = addrinfo;
314     return 1;
315 }         
316
317 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
318     char *p, *field;
319     int ipv6 = 0;
320
321     p = s;
322     /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
323     if (*p == '[') {
324         p++;
325         field = p;
326         for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
327         if (*p != ']')
328             debugx(1, DBG_ERR, "no ] matching initial [");
329         ipv6 = 1;
330     } else {
331         field = p;
332         for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
333     }
334     if (field == p)
335         debugx(1, DBG_ERR, "missing host/address");
336
337     conf->host = stringcopy(field, p - field);
338     if (ipv6) {
339         p++;
340         if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
341             debugx(1, DBG_ERR, "unexpected character after ]");
342     }
343     if (*p == ':') {
344             /* port number or service name is specified */;
345             field = ++p;
346             for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
347             if (field == p)
348                 debugx(1, DBG_ERR, "syntax error, : but no following port");
349             conf->port = stringcopy(field, p - field);
350     } else
351         conf->port = default_port ? stringcopy(default_port, 0) : NULL;
352     return p;
353 }
354
355 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
356     struct clsrvconf *conf;
357
358     conf = malloc(sizeof(struct clsrvconf));
359     if (!conf)
360         debugx(1, DBG_ERR, "malloc failed");
361     memset(conf, 0, sizeof(struct clsrvconf));
362     conf->type = type;
363     conf->pdef = &protodefs[conf->type];
364     if (lconf) {
365         parsehostport(lconf, conf, default_port);
366         if (!strcmp(conf->host, "*")) {
367             free(conf->host);
368             conf->host = NULL;
369         }
370     } else
371         conf->port = default_port ? stringcopy(default_port, 0) : NULL;
372     if (!resolvepeer(conf, AI_PASSIVE))
373         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
374     return conf;
375 }
376
377 void freeclsrvres(struct clsrvconf *res) {
378     free(res->host);
379     free(res->port);
380     if (res->addrinfo)
381         freeaddrinfo(res->addrinfo);
382     free(res);
383 }
384
385 int connecttcp(struct addrinfo *addrinfo, struct addrinfo *src) {
386     int s;
387     struct addrinfo *res;
388
389     s = -1;
390     for (res = addrinfo; res; res = res->ai_next) {
391         s = bindtoaddr(src, res->ai_family, 1, 1);
392         if (s < 0) {
393             debug(DBG_WARN, "connecttoserver: socket failed");
394             continue;
395         }
396         if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
397             break;
398         debug(DBG_WARN, "connecttoserver: connect failed");
399         close(s);
400         s = -1;
401     }
402     return s;
403 }         
404
405 /* returns 1 if the len first bits are equal, else 0 */
406 int prefixmatch(void *a1, void *a2, uint8_t len) {
407     static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
408     int r, l = len / 8;
409     if (l && memcmp(a1, a2, l))
410         return 0;
411     r = len % 8;
412     if (!r)
413         return 1;
414     return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
415 }
416
417 /* returns next config with matching address, or NULL */
418 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
419     struct sockaddr_in6 *sa6 = NULL;
420     struct in_addr *a4 = NULL;
421     struct addrinfo *res;
422     struct list_node *entry;
423     struct clsrvconf *conf;
424     
425     if (addr->sa_family == AF_INET6) {
426         sa6 = (struct sockaddr_in6 *)addr;
427         if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
428             a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
429             sa6 = NULL;
430         }
431     } else
432         a4 = &((struct sockaddr_in *)addr)->sin_addr;
433
434     for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
435         conf = (struct clsrvconf *)entry->data;
436         if (conf->type == type) {
437             if (conf->prefixlen == 255) {
438                 for (res = conf->addrinfo; res; res = res->ai_next)
439                     if ((a4 && res->ai_family == AF_INET &&
440                          !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
441                         (sa6 && res->ai_family == AF_INET6 &&
442                          !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
443                         if (cur)
444                             *cur = entry;
445                         return conf;
446                     }
447             } else {
448                 res = conf->addrinfo;
449                 if (res &&
450                     ((a4 && res->ai_family == AF_INET &&
451                       prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
452                      (sa6 && res->ai_family == AF_INET6 &&
453                       prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
454                     if (cur)
455                         *cur = entry;
456                     return conf;
457                 }
458             }
459         }
460     }    
461     return NULL;
462 }
463
464 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
465     return find_conf(type, addr, clconfs, cur);
466 }
467
468 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
469     return find_conf(type, addr, srvconfs, cur);
470 }
471
472 /* returns next config of given type, or NULL */
473 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
474     struct list_node *entry;
475     struct clsrvconf *conf;
476     
477     for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
478         conf = (struct clsrvconf *)entry->data;
479         if (conf->type == type) {
480             if (cur)
481                 *cur = entry;
482             return conf;
483         }
484     }    
485     return NULL;
486 }
487
488 struct queue *newqueue() {
489     struct queue *q;
490     
491     q = malloc(sizeof(struct queue));
492     if (!q)
493         debugx(1, DBG_ERR, "malloc failed");
494     q->entries = list_create();
495     if (!q->entries)
496         debugx(1, DBG_ERR, "malloc failed");
497     pthread_mutex_init(&q->mutex, NULL);
498     pthread_cond_init(&q->cond, NULL);
499     return q;
500 }
501
502 void removequeue(struct queue *q) {
503     struct list_node *entry;
504     
505     pthread_mutex_lock(&q->mutex);
506     for (entry = list_first(q->entries); entry; entry = list_next(entry))
507         free(((struct reply *)entry)->buf);
508     list_destroy(q->entries);
509     pthread_cond_destroy(&q->cond);
510     pthread_mutex_unlock(&q->mutex);
511     pthread_mutex_destroy(&q->mutex);
512 }
513
514 void freebios(struct queue *q) {
515     BIO *bio;
516     
517     pthread_mutex_lock(&q->mutex);
518     while ((bio = (BIO *)list_shift(q->entries)))
519         BIO_free(bio);
520     pthread_mutex_unlock(&q->mutex);
521     removequeue(q);
522 }
523
524 struct client *addclient(struct clsrvconf *conf) {
525     struct client *new = malloc(sizeof(struct client));
526     
527     if (!new) {
528         debug(DBG_ERR, "malloc failed");
529         return NULL;
530     }
531     if (!conf->clients) {
532         conf->clients = list_create();
533         if (!conf->clients) {
534             debug(DBG_ERR, "malloc failed");
535             return NULL;
536         }
537     }
538     
539     memset(new, 0, sizeof(struct client));
540     new->conf = conf;
541     if (conf->pdef->addclient)
542         conf->pdef->addclient(new);
543     else
544         new->replyq = newqueue();
545     list_push(conf->clients, new);
546     return new;
547 }
548
549 void removeclient(struct client *client) {
550     if (!client || !client->conf->clients)
551         return;
552     removequeue(client->replyq);
553     if (client->rbios)
554         freebios(client->rbios);
555     list_removedata(client->conf->clients, client);
556     free(client);
557 }
558
559 void removeclientrqs(struct client *client) {
560     struct list_node *entry;
561     struct server *server;
562     struct request *rq;
563     int i;
564     
565     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
566         server = ((struct clsrvconf *)entry->data)->servers;
567         if (!server)
568             continue;
569         pthread_mutex_lock(&server->newrq_mutex);
570         for (i = 0; i < MAX_REQUESTS; i++) {
571             rq = server->requests + i;
572             if (rq->from == client)
573                 rq->from = NULL;
574         }
575         pthread_mutex_unlock(&server->newrq_mutex);
576     }
577 }
578
579 void freeserver(struct server *server, uint8_t destroymutex) {
580     struct request *rq, *end;
581
582     if (!server)
583         return;
584
585     if (server->requests) {
586         rq = server->requests;
587         for (end = rq + MAX_REQUESTS; rq < end; rq++)
588             freerqdata(rq);
589         free(server->requests);
590     }
591     if (server->rbios)
592         freebios(server->rbios);
593     free(server->dynamiclookuparg);
594     if (destroymutex) {
595         pthread_mutex_destroy(&server->lock);
596         pthread_cond_destroy(&server->newrq_cond);
597         pthread_mutex_destroy(&server->newrq_mutex);
598     }
599     free(server);
600 }
601
602 int addserver(struct clsrvconf *conf) {
603     struct clsrvconf *res;
604     uint8_t type;
605     
606     if (conf->servers) {
607         debug(DBG_ERR, "addserver: currently works with just one server per conf");
608         return 0;
609     }
610     conf->servers = malloc(sizeof(struct server));
611     if (!conf->servers) {
612         debug(DBG_ERR, "malloc failed");
613         return 0;
614     }
615     memset(conf->servers, 0, sizeof(struct server));
616     conf->servers->conf = conf;
617
618     type = conf->type;
619     if (type == RAD_DTLS)
620         conf->servers->rbios = newqueue();
621     
622     if (!srcprotores[type]) {
623         res = resolve_hostport(type, *conf->pdef->srcaddrport, NULL);
624         srcprotores[type] = res->addrinfo;
625         res->addrinfo = NULL;
626         freeclsrvres(res);
627     }
628
629     conf->servers->sock = -1;
630     if (conf->pdef->addserverextra)
631         conf->pdef->addserverextra(conf);
632     
633     conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
634     if (!conf->servers->requests) {
635         debug(DBG_ERR, "malloc failed");
636         goto errexit;
637     }
638     if (pthread_mutex_init(&conf->servers->lock, NULL)) {
639         debug(DBG_ERR, "mutex init failed");
640         goto errexit;
641     }
642     conf->servers->newrq = 0;
643     if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
644         debug(DBG_ERR, "mutex init failed");
645         pthread_mutex_destroy(&conf->servers->lock);
646         goto errexit;
647     }
648     if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
649         debug(DBG_ERR, "mutex init failed");
650         pthread_mutex_destroy(&conf->servers->newrq_mutex);
651         pthread_mutex_destroy(&conf->servers->lock);
652         goto errexit;
653     }
654
655     return 1;
656     
657  errexit:
658     freeserver(conf->servers, 0);
659     conf->servers = NULL;
660     return 0;
661 }
662
663 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
664     int loc, i, l, n, r = 0;
665     char *v;
666     X509_EXTENSION *ex;
667     STACK_OF(GENERAL_NAME) *alt;
668     GENERAL_NAME *gn;
669     
670     debug(DBG_DBG, "subjectaltnameaddr");
671     
672     loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
673     if (loc < 0)
674         return r;
675     
676     ex = X509_get_ext(cert, loc);
677     alt = X509V3_EXT_d2i(ex);
678     if (!alt)
679         return r;
680     
681     n = sk_GENERAL_NAME_num(alt);
682     for (i = 0; i < n; i++) {
683         gn = sk_GENERAL_NAME_value(alt, i);
684         if (gn->type != GEN_IPADD)
685             continue;
686         r = -1;
687         v = (char *)ASN1_STRING_data(gn->d.ia5);
688         l = ASN1_STRING_length(gn->d.ia5);
689         if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
690             && !memcmp(v, &addr, l)) {
691             r = 1;
692             break;
693         }
694     }
695     GENERAL_NAMES_free(alt);
696     return r;
697 }
698
699 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
700     int loc, l;
701     char *v, *s;
702     X509_NAME *nm;
703     X509_NAME_ENTRY *e;
704     ASN1_STRING *t;
705
706     nm = X509_get_subject_name(cert);
707     loc = -1;
708     for (;;) {
709         loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
710         if (loc == -1)
711             break;
712         e = X509_NAME_get_entry(nm, loc);
713         t = X509_NAME_ENTRY_get_data(e);
714         v = (char *) ASN1_STRING_data(t);
715         l = ASN1_STRING_length(t);
716         if (l < 0)
717             continue;
718         if (exact) {
719             if (l == strlen(exact) && !strncasecmp(exact, v, l))
720                 return 1;
721         } else {
722             s = stringcopy((char *)v, l);
723             if (!s) {
724                 debug(DBG_ERR, "malloc failed");
725                 continue;
726             }
727             if (regexec(regex, s, 0, NULL, 0)) {
728                 free(s);
729                 continue;
730             }
731             free(s);
732             return 1;
733         }
734     }
735     return 0;
736 }
737
738 int subjectaltnameregexp(X509 *cert, int type, char *exact,  regex_t *regex) {
739     int loc, i, l, n, r = 0;
740     char *s, *v;
741     X509_EXTENSION *ex;
742     STACK_OF(GENERAL_NAME) *alt;
743     GENERAL_NAME *gn;
744     
745     debug(DBG_DBG, "subjectaltnameregexp");
746     
747     loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
748     if (loc < 0)
749         return r;
750     
751     ex = X509_get_ext(cert, loc);
752     alt = X509V3_EXT_d2i(ex);
753     if (!alt)
754         return r;
755     
756     n = sk_GENERAL_NAME_num(alt);
757     for (i = 0; i < n; i++) {
758         gn = sk_GENERAL_NAME_value(alt, i);
759         if (gn->type != type)
760             continue;
761         r = -1;
762         v = (char *)ASN1_STRING_data(gn->d.ia5);
763         l = ASN1_STRING_length(gn->d.ia5);
764         if (l <= 0)
765             continue;
766 #ifdef DEBUG
767         printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
768 #endif  
769         if (exact) {
770             if (memcmp(v, exact, l))
771                 continue;
772         } else {
773             s = stringcopy((char *)v, l);
774             if (!s) {
775                 debug(DBG_ERR, "malloc failed");
776                 continue;
777             }
778             if (regexec(regex, s, 0, NULL, 0)) {
779                 free(s);
780                 continue;
781             }
782             free(s);
783         }
784         r = 1;
785         break;
786     }
787     GENERAL_NAMES_free(alt);
788     return r;
789 }
790
791 X509 *verifytlscert(SSL *ssl) {
792     X509 *cert;
793     unsigned long error;
794     
795     if (SSL_get_verify_result(ssl) != X509_V_OK) {
796         debug(DBG_ERR, "verifytlscert: basic validation failed");
797         while ((error = ERR_get_error()))
798             debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
799         return NULL;
800     }
801
802     cert = SSL_get_peer_certificate(ssl);
803     if (!cert)
804         debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
805     return cert;
806 }
807     
808 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
809     int r;
810     uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
811     struct in6_addr addr;
812     
813     if (conf->certnamecheck && conf->prefixlen == 255) {
814         if (inet_pton(AF_INET, conf->host, &addr))
815             type = AF_INET;
816         else if (inet_pton(AF_INET6, conf->host, &addr))
817             type = AF_INET6;
818
819         r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
820         if (r) {
821             if (r < 0) {
822                 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
823                 return 0;
824             }
825             debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
826         } else {
827             if (!cnregexp(cert, conf->host, NULL)) {
828                 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
829                 return 0;
830             }           
831             debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
832         }
833     }
834     if (conf->certcnregex) {
835         if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
836             debug(DBG_WARN, "verifyconfcert: CN not matching regex");
837             return 0;
838         }
839         debug(DBG_DBG, "verifyconfcert: CN matching regex");
840     }
841     if (conf->certuriregex) {
842         if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
843             debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
844             return 0;
845         }
846         debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
847     }
848     return 1;
849 }
850
851 int radsign(unsigned char *rad, unsigned char *sec) {
852     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
853     static unsigned char first = 1;
854     static EVP_MD_CTX mdctx;
855     unsigned int md_len;
856     int result;
857     
858     pthread_mutex_lock(&lock);
859     if (first) {
860         EVP_MD_CTX_init(&mdctx);
861         first = 0;
862     }
863
864     result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
865         EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
866         EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
867         EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
868         md_len == 16);
869     pthread_mutex_unlock(&lock);
870     return result;
871 }
872
873 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
874     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
875     static unsigned char first = 1;
876     static EVP_MD_CTX mdctx;
877     unsigned char hash[EVP_MAX_MD_SIZE];
878     unsigned int len;
879     int result;
880     
881     pthread_mutex_lock(&lock);
882     if (first) {
883         EVP_MD_CTX_init(&mdctx);
884         first = 0;
885     }
886
887     len = RADLEN(rad);
888     
889     result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
890               EVP_DigestUpdate(&mdctx, rad, 4) &&
891               EVP_DigestUpdate(&mdctx, reqauth, 16) &&
892               (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
893               EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
894               EVP_DigestFinal_ex(&mdctx, hash, &len) &&
895               len == 16 &&
896               !memcmp(hash, rad + 4, 16));
897     pthread_mutex_unlock(&lock);
898     return result;
899 }
900               
901 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
902     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
903     static unsigned char first = 1;
904     static HMAC_CTX hmacctx;
905     unsigned int md_len;
906     uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
907     
908     pthread_mutex_lock(&lock);
909     if (first) {
910         HMAC_CTX_init(&hmacctx);
911         first = 0;
912     }
913
914     memcpy(auth, authattr, 16);
915     memset(authattr, 0, 16);
916     md_len = 0;
917     HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
918     HMAC_Update(&hmacctx, rad, RADLEN(rad));
919     HMAC_Final(&hmacctx, hash, &md_len);
920     memcpy(authattr, auth, 16);
921     if (md_len != 16) {
922         debug(DBG_WARN, "message auth computation failed");
923         pthread_mutex_unlock(&lock);
924         return 0;
925     }
926
927     if (memcmp(auth, hash, 16)) {
928         debug(DBG_WARN, "message authenticator, wrong value");
929         pthread_mutex_unlock(&lock);
930         return 0;
931     }   
932         
933     pthread_mutex_unlock(&lock);
934     return 1;
935 }
936
937 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
938     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
939     static unsigned char first = 1;
940     static HMAC_CTX hmacctx;
941     unsigned int md_len;
942
943     if (!authattrval)
944         return 1;
945     
946     pthread_mutex_lock(&lock);
947     if (first) {
948         HMAC_CTX_init(&hmacctx);
949         first = 0;
950     }
951
952     memset(authattrval, 0, 16);
953     md_len = 0;
954     HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
955     HMAC_Update(&hmacctx, rad, RADLEN(rad));
956     HMAC_Final(&hmacctx, authattrval, &md_len);
957     if (md_len != 16) {
958         debug(DBG_WARN, "message auth computation failed");
959         pthread_mutex_unlock(&lock);
960         return 0;
961     }
962
963     pthread_mutex_unlock(&lock);
964     return 1;
965 }
966
967 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
968     while (length > 1) {
969         if (ATTRTYPE(attrs) == type)
970             return attrs;
971         length -= ATTRLEN(attrs);
972         attrs += ATTRLEN(attrs);
973     }
974     return NULL;
975 }
976
977 void freerqdata(struct request *rq) {
978     if (rq->origusername)
979         free(rq->origusername);
980     if (rq->buf)
981         free(rq->buf);
982 }
983
984 void sendrq(struct server *to, struct request *rq) {
985     int i;
986     uint8_t *attr;
987
988     pthread_mutex_lock(&to->newrq_mutex);
989     /* might simplify if only try nextid, might be ok */
990     for (i = to->nextid; i < MAX_REQUESTS; i++)
991         if (!to->requests[i].buf)
992             break;
993     if (i == MAX_REQUESTS) {
994         for (i = 0; i < to->nextid; i++)
995             if (!to->requests[i].buf)
996                 break;
997         if (i == to->nextid) {
998             debug(DBG_WARN, "sendrq: no room in queue, dropping request");
999             freerqdata(rq);
1000             goto exit;
1001         }
1002     }
1003     
1004     rq->buf[1] = (char)i;
1005
1006     attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1007     if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1008         freerqdata(rq);
1009         goto exit;
1010     }
1011     
1012     if (*rq->buf == RAD_Accounting_Request) {
1013         if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
1014             debug(DBG_WARN, "sendrq: failed to sign Accounting-Request message");
1015             freerqdata(rq);
1016             goto exit;
1017         }
1018     }
1019
1020     debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1021     to->requests[i] = *rq;
1022     to->nextid = i + 1;
1023
1024     if (!to->newrq) {
1025         to->newrq = 1;
1026         debug(DBG_DBG, "sendrq: signalling client writer");
1027         pthread_cond_signal(&to->newrq_cond);
1028     }
1029  exit:
1030     pthread_mutex_unlock(&to->newrq_mutex);
1031 }
1032
1033 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa, int toudpsock) {
1034     struct reply *reply;
1035     uint8_t first;
1036     
1037     if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1038         free(buf);
1039         debug(DBG_WARN, "sendreply: failed to sign message");
1040         return;
1041     }
1042
1043     reply = malloc(sizeof(struct reply));
1044     if (!reply) {
1045         free(buf);
1046         debug(DBG_ERR, "sendreply: malloc failed");
1047         return;
1048     }
1049     memset(reply, 0, sizeof(struct reply));
1050     reply->buf = buf;
1051     if (tosa)
1052         reply->tosa = *tosa;
1053     reply->toudpsock = toudpsock;
1054     
1055     pthread_mutex_lock(&to->replyq->mutex);
1056
1057     first = list_first(to->replyq->entries) == NULL;
1058     
1059     if (!list_push(to->replyq->entries, reply)) {
1060         pthread_mutex_unlock(&to->replyq->mutex);
1061         free(reply);
1062         free(buf);
1063         debug(DBG_ERR, "sendreply: malloc failed");
1064         return;
1065     }
1066     
1067     if (first) {
1068         debug(DBG_DBG, "signalling server writer");
1069         pthread_cond_signal(&to->replyq->cond);
1070     }
1071     pthread_mutex_unlock(&to->replyq->mutex);
1072 }
1073
1074 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1075     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1076     static unsigned char first = 1;
1077     static EVP_MD_CTX mdctx;
1078     unsigned char hash[EVP_MAX_MD_SIZE], *input;
1079     unsigned int md_len;
1080     uint8_t i, offset = 0, out[128];
1081     
1082     pthread_mutex_lock(&lock);
1083     if (first) {
1084         EVP_MD_CTX_init(&mdctx);
1085         first = 0;
1086     }
1087
1088     input = auth;
1089     for (;;) {
1090         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1091             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1092             !EVP_DigestUpdate(&mdctx, input, 16) ||
1093             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1094             md_len != 16) {
1095             pthread_mutex_unlock(&lock);
1096             return 0;
1097         }
1098         for (i = 0; i < 16; i++)
1099             out[offset + i] = hash[i] ^ in[offset + i];
1100         input = out + offset - 16;
1101         offset += 16;
1102         if (offset == len)
1103             break;
1104     }
1105     memcpy(in, out, len);
1106     pthread_mutex_unlock(&lock);
1107     return 1;
1108 }
1109
1110 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1111     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1112     static unsigned char first = 1;
1113     static EVP_MD_CTX mdctx;
1114     unsigned char hash[EVP_MAX_MD_SIZE], *input;
1115     unsigned int md_len;
1116     uint8_t i, offset = 0, out[128];
1117     
1118     pthread_mutex_lock(&lock);
1119     if (first) {
1120         EVP_MD_CTX_init(&mdctx);
1121         first = 0;
1122     }
1123
1124     input = auth;
1125     for (;;) {
1126         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1127             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1128             !EVP_DigestUpdate(&mdctx, input, 16) ||
1129             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1130             md_len != 16) {
1131             pthread_mutex_unlock(&lock);
1132             return 0;
1133         }
1134         for (i = 0; i < 16; i++)
1135             out[offset + i] = hash[i] ^ in[offset + i];
1136         input = in + offset;
1137         offset += 16;
1138         if (offset == len)
1139             break;
1140     }
1141     memcpy(in, out, len);
1142     pthread_mutex_unlock(&lock);
1143     return 1;
1144 }
1145
1146 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1147     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1148     static unsigned char first = 1;
1149     static EVP_MD_CTX mdctx;
1150     unsigned char hash[EVP_MAX_MD_SIZE];
1151     unsigned int md_len;
1152     uint8_t i, offset;
1153     
1154     pthread_mutex_lock(&lock);
1155     if (first) {
1156         EVP_MD_CTX_init(&mdctx);
1157         first = 0;
1158     }
1159
1160 #if 0
1161     printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1162     printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1163     printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1164 #endif
1165     
1166     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1167         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1168         !EVP_DigestUpdate(&mdctx, auth, 16) ||
1169         !EVP_DigestUpdate(&mdctx, salt, 2) ||
1170         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1171         pthread_mutex_unlock(&lock);
1172         return 0;
1173     }
1174
1175 #if 0    
1176     printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1177 #endif
1178     
1179     for (i = 0; i < 16; i++)
1180         text[i] ^= hash[i];
1181     
1182     for (offset = 16; offset < len; offset += 16) {
1183 #if 0   
1184         printf("text + offset - 16 c(%d): ", offset / 16);
1185         printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1186 #endif
1187         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1188             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1189             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1190             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1191             md_len != 16) {
1192             pthread_mutex_unlock(&lock);
1193             return 0;
1194         }
1195 #if 0
1196         printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1197 #endif    
1198         
1199         for (i = 0; i < 16; i++)
1200             text[offset + i] ^= hash[i];
1201     }
1202     
1203 #if 0
1204     printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1205 #endif
1206
1207     pthread_mutex_unlock(&lock);
1208     return 1;
1209 }
1210
1211 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1212     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1213     static unsigned char first = 1;
1214     static EVP_MD_CTX mdctx;
1215     unsigned char hash[EVP_MAX_MD_SIZE];
1216     unsigned int md_len;
1217     uint8_t i, offset;
1218     char plain[255];
1219     
1220     pthread_mutex_lock(&lock);
1221     if (first) {
1222         EVP_MD_CTX_init(&mdctx);
1223         first = 0;
1224     }
1225
1226 #if 0
1227     printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1228     printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1229     printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1230 #endif
1231     
1232     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1233         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1234         !EVP_DigestUpdate(&mdctx, auth, 16) ||
1235         !EVP_DigestUpdate(&mdctx, salt, 2) ||
1236         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1237         pthread_mutex_unlock(&lock);
1238         return 0;
1239     }
1240
1241 #if 0    
1242     printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1243 #endif
1244     
1245     for (i = 0; i < 16; i++)
1246         plain[i] = text[i] ^ hash[i];
1247     
1248     for (offset = 16; offset < len; offset += 16) {
1249 #if 0   
1250         printf("text + offset - 16 c(%d): ", offset / 16);
1251         printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1252 #endif
1253         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1254             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1255             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1256             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1257             md_len != 16) {
1258             pthread_mutex_unlock(&lock);
1259             return 0;
1260         }
1261 #if 0
1262         printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1263 #endif    
1264
1265         for (i = 0; i < 16; i++)
1266             plain[offset + i] = text[offset + i] ^ hash[i];
1267     }
1268
1269     memcpy(text, plain, len);
1270 #if 0
1271     printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1272 #endif
1273
1274     pthread_mutex_unlock(&lock);
1275     return 1;
1276 }
1277
1278 struct realm *id2realm(struct list *realmlist, char *id) {
1279     struct list_node *entry;
1280     struct realm *realm, *subrealm = NULL;
1281
1282     /* need to do locking for subrealms and check subrealm timers */
1283     for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1284         realm = (struct realm *)entry->data;
1285         if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1286             pthread_mutex_lock(&realm->subrealms_mutex);
1287             if (realm->subrealms)
1288                 subrealm = id2realm(realm->subrealms, id);
1289             pthread_mutex_unlock(&realm->subrealms_mutex);
1290             return subrealm ? subrealm : realm;
1291         }
1292     }
1293     return NULL;
1294 }
1295
1296 /* helper function, only used by removeserversubrealms() */
1297 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1298     struct list_node *entry;
1299     struct realm *realm;
1300     
1301     for (entry = list_first(realmlist); entry;) {
1302         realm = (struct realm *)entry->data;
1303         entry = list_next(entry);
1304         if (realm->srvconfs) {
1305             list_removedata(realm->srvconfs, srv);
1306             if (!list_first(realm->srvconfs)) {
1307                 list_destroy(realm->srvconfs);
1308                 realm->srvconfs = NULL;
1309             }
1310         }
1311         if (realm->accsrvconfs) {
1312             list_removedata(realm->accsrvconfs, srv);
1313             if (!list_first(realm->accsrvconfs)) {
1314                 list_destroy(realm->accsrvconfs);
1315                 realm->accsrvconfs = NULL;
1316             }
1317         }
1318
1319         /* remove subrealm if no servers */
1320         if (!realm->srvconfs && !realm->accsrvconfs) {
1321             list_removedata(realmlist, realm);
1322             freerealm(realm);
1323         }
1324     }
1325 }
1326
1327 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1328     struct list_node *entry;
1329     struct realm *realm;
1330     
1331     for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1332         realm = (struct realm *)entry->data;
1333         pthread_mutex_lock(&realm->subrealms_mutex);
1334         if (realm->subrealms) {
1335             _internal_removeserversubrealms(realm->subrealms, srv);
1336             if (!list_first(realm->subrealms)) {
1337                 list_destroy(realm->subrealms);
1338                 realm->subrealms = NULL;
1339             }
1340         }
1341         pthread_mutex_unlock(&realm->subrealms_mutex);
1342     }
1343 }
1344                         
1345 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1346     struct request *rq = to->requests, *end;
1347     
1348     pthread_mutex_lock(&to->newrq_mutex);
1349     for (end = rq + MAX_REQUESTS; rq < end; rq++)
1350         if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1351             break;
1352     pthread_mutex_unlock(&to->newrq_mutex);
1353     
1354     return rq < end;
1355 }
1356
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));
1361             return 0;
1362         }
1363         length -= ATTRLEN(attrs);
1364         if (length < 0) {
1365             debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1366             return 0;
1367         }
1368         attrs += ATTRLEN(attrs);
1369     }
1370     if (length)
1371         debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1372     return 1;
1373 }
1374
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");
1378         return 0;
1379     }
1380         
1381     if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1382         debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1383         return 0;
1384     }
1385 #ifdef DEBUG
1386     printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1387 #endif  
1388     if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1389         debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1390         return 0;
1391     }
1392     return 1;
1393 }
1394
1395 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1396     if (len < 18)
1397         return 0;
1398     if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1399         debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1400         return 0;
1401     }
1402     if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1403         debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1404         return 0;
1405     }
1406     return 1;
1407 }
1408
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;
1412     
1413     for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1414         debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1415         if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1416             return 0;
1417     }
1418     return 1;
1419 }
1420
1421 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1422     if (!attrs)
1423         return 0;
1424     
1425     for (; attrs[0]; attrs += 2)
1426         if (attrs[0] == vendor && attrs[1] == subattr)
1427             return 1;
1428     return 0;
1429 }
1430
1431 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1432     uint8_t alen, sublen, rmlen = 0;
1433     uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1434     uint8_t *subattrs;
1435     
1436     if (!removevendorattrs)
1437         return 0;
1438
1439     while (*removevendorattrs && *removevendorattrs != vendor)
1440         removevendorattrs += 2;
1441     if (!*removevendorattrs)
1442         return 0;
1443     
1444     alen = ATTRLEN(attrs);
1445
1446     if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1447         /* remove entire vendor attribute */
1448         memmove(attrs, attrs + alen, length - alen);
1449         return alen;
1450     }
1451
1452     sublen = alen - 4;
1453     subattrs = ATTRVAL(attrs) + 4;
1454     
1455     if (!attrvalidate(subattrs, sublen)) {
1456         debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1457         return 0;
1458     }
1459
1460     length -= 6;
1461     while (sublen > 1) {
1462         alen = ATTRLEN(subattrs);
1463         sublen -= alen;
1464         length -= alen;
1465         if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1466             memmove(subattrs, subattrs + alen, length);
1467             rmlen += alen;
1468         } else
1469             subattrs += alen;
1470     }
1471
1472     ATTRLEN(attrs) -= rmlen;
1473     return rmlen;
1474 }
1475
1476 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1477     uint8_t *attrs, alen;
1478     uint16_t len, rmlen = 0;
1479     
1480     if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1481         return;
1482
1483     len = RADLEN(buf) - 20;
1484     attrs = buf + 20;
1485     while (len > 1) {
1486         alen = ATTRLEN(attrs);
1487         len -= alen;
1488         if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1489             memmove(attrs, attrs + alen, len);
1490             rmlen += alen;
1491         } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1492             rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1493         else
1494             attrs += alen;
1495     }
1496     if (rmlen)
1497         ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1498 }
1499
1500 /* returns a pointer to the resized attribute value */
1501 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1502     uint8_t *attrs, *attr, vallen;
1503     uint16_t len;
1504     unsigned char *new;
1505     
1506     len = RADLEN(*buf) - 20;
1507     attrs = *buf + 20;
1508
1509     attr = attrget(attrs, len, type);
1510     if (!attr)
1511         return NULL;
1512     
1513     vallen = ATTRVALLEN(attr);
1514     if (vallen == newvallen)
1515         return attr + 2;
1516
1517     len += newvallen - vallen;
1518     if (newvallen > vallen) {
1519         new = realloc(*buf, len + 20);
1520         if (!new) {
1521             debug(DBG_ERR, "resizeattr: malloc failed");
1522             return NULL;
1523         }
1524         if (new != *buf) {
1525             attr += new - *buf;
1526             attrs = new + 20;
1527             *buf = new;
1528         }
1529     }
1530     memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1531     attr[1] = newvallen + 2;
1532     ((uint16_t *)*buf)[1] = htons(len + 20);
1533     return attr + 2;
1534 }
1535                 
1536 int rewriteusername(struct request *rq, char *in) {
1537     size_t nmatch = 10, reslen = 0, start = 0;
1538     regmatch_t pmatch[10], *pfield;
1539     int i;
1540     unsigned char *result;
1541     char *out = rq->from->conf->rewriteattrreplacement;
1542     
1543     if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1544         debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1545         return 1;
1546     }
1547     
1548     rq->origusername = stringcopy(in, 0);
1549     if (!rq->origusername)
1550         return 0;
1551     
1552     for (i = start; out[i]; i++) {
1553         if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1554             pfield = &pmatch[out[i + 1] - '0'];
1555             if (pfield->rm_so >= 0) {
1556                 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1557                 start = i + 2;
1558             }
1559             i++;
1560         }
1561     }
1562     reslen += i - start;
1563
1564     result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1565     if (!result)
1566         return 0;
1567     
1568     start = 0;
1569     reslen = 0;
1570     for (i = start; out[i]; i++) {
1571         if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1572             pfield = &pmatch[out[i + 1] - '0'];
1573             if (pfield->rm_so >= 0) {
1574                 memcpy(result + reslen, out + start, i - start);
1575                 reslen += i - start;
1576                 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1577                 reslen += pfield->rm_eo - pfield->rm_so;
1578                 start = i + 2;
1579             }
1580             i++;
1581         }
1582     }
1583
1584     memcpy(result + reslen, out + start, i - start);
1585     reslen += i - start;
1586     memcpy(in, result, reslen);
1587     in[reslen] = '\0';
1588     return 1;
1589 }
1590
1591 const char *radmsgtype2string(uint8_t code) {
1592     static const char *rad_msg_names[] = {
1593         "", "Access-Request", "Access-Accept", "Access-Reject",
1594         "Accounting-Request", "Accounting-Response", "", "",
1595         "", "", "", "Access-Challenge",
1596         "Status-Server", "Status-Client"
1597     };
1598     return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1599 }
1600
1601 void char2hex(char *h, unsigned char c) {
1602     static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1603                                       '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1604     h[0] = hexdigits[c / 16];
1605     h[1] = hexdigits[c % 16];
1606     return;
1607 }
1608
1609 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
1610     int i, l;
1611     char *s, *d;
1612
1613     if (!attr || len == 1) {
1614         *ascii = '\0';
1615         return ascii;
1616     }
1617
1618     l = ATTRVALLEN(attr);
1619     s = (char *)ATTRVAL(attr);
1620     d = ascii;
1621
1622     for (i = 0; i < l; i++) {
1623         if (s[i] > 31 && s[i] < 127) {
1624             *d++ = s[i];
1625             if (d - ascii == len - 1)
1626                 break;
1627         } else {
1628             if (d - ascii > len - 4)
1629                 break;
1630             *d++ = '%';
1631             char2hex(d, s[i]);
1632             d += 2;
1633             if (d - ascii == len - 1)
1634                 break;
1635         }
1636     }
1637     *d = '\0';
1638     return ascii;
1639 }
1640
1641 void acclog(unsigned char *attrs, int length, char *host) {
1642     unsigned char *attr;
1643     char username[760];
1644     
1645     attr = attrget(attrs, length, RAD_Attr_User_Name);
1646     if (!attr) {
1647         debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1648         return;
1649     }
1650     radattr2ascii(username, sizeof(username), attr);
1651     debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1652 }
1653         
1654 void respondaccounting(struct request *rq) {
1655     unsigned char *resp;
1656
1657     resp = malloc(20);
1658     if (!resp) {
1659         debug(DBG_ERR, "respondaccounting: malloc failed");
1660         return;
1661     }
1662     memcpy(resp, rq->buf, 20);
1663     resp[0] = RAD_Accounting_Response;
1664     resp[2] = 0;
1665     resp[3] = 20;
1666     debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1667     sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1668 }
1669
1670 void respondstatusserver(struct request *rq) {
1671     unsigned char *resp;
1672
1673     resp = malloc(20);
1674     if (!resp) {
1675         debug(DBG_ERR, "respondstatusserver: malloc failed");
1676         return;
1677     }
1678     memcpy(resp, rq->buf, 20);
1679     resp[0] = RAD_Access_Accept;
1680     resp[2] = 0;
1681     resp[3] = 20;
1682     debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1683     sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1684 }
1685
1686 void respondreject(struct request *rq, char *message) {
1687     unsigned char *resp;
1688     int len = 20;
1689
1690     if (message && *message)
1691         len += 2 + strlen(message);
1692     
1693     resp = malloc(len);
1694     if (!resp) {
1695         debug(DBG_ERR, "respondreject: malloc failed");
1696         return;
1697     }
1698     memcpy(resp, rq->buf, 20);
1699     resp[0] = RAD_Access_Reject;
1700     *(uint16_t *)(resp + 2) = htons(len);
1701     if (message && *message) {
1702         resp[20] = RAD_Attr_Reply_Message;
1703         resp[21] = len - 20;
1704         memcpy(resp + 22, message, len - 22);
1705     }
1706     sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1707 }
1708
1709 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1710     struct list_node *entry;
1711     struct clsrvconf *server, *best = NULL, *first = NULL;
1712
1713     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1714         server = (struct clsrvconf *)entry->data;
1715         if (!server->servers)
1716             return server;
1717         if (!first)
1718             first = server;
1719         if (!server->servers->connectionok)
1720             continue;
1721         if (!server->servers->lostrqs)
1722             return server;
1723         if (!best) {
1724             best = server;
1725             continue;
1726         }
1727         if (server->servers->lostrqs < best->servers->lostrqs)
1728             best = server;
1729     }
1730     return best ? best : first;
1731 }
1732
1733 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
1734     struct clsrvconf *srvconf;
1735     
1736     *realm = id2realm(realms, id);
1737     if (!*realm)
1738         return NULL;
1739     debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1740     srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1741     if (!srvconf)
1742         return NULL;
1743     if (!acc && !srvconf->servers)
1744         adddynamicrealmserver(*realm, srvconf, id);
1745     return srvconf->servers;
1746 }
1747
1748 /* returns 0 if validation/authentication fails, else 1 */
1749 int radsrv(struct request *rq) {
1750     uint8_t code, id, *auth, *attrs, *attr;
1751     uint16_t len;
1752     struct server *to = NULL;
1753     char username[254], userascii[760];
1754     unsigned char newauth[16];
1755     struct realm *realm = NULL;
1756     
1757     code = *(uint8_t *)rq->buf;
1758     id = *(uint8_t *)(rq->buf + 1);
1759     len = RADLEN(rq->buf);
1760     auth = (uint8_t *)(rq->buf + 4);
1761
1762     debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1763     
1764     if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1765         debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1766         goto exit;
1767     }
1768
1769     len -= 20;
1770     attrs = rq->buf + 20;
1771
1772     if (!attrvalidate(attrs, len)) {
1773         debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1774         goto errvalauth;
1775     }
1776
1777     attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1778     if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
1779         debug(DBG_WARN, "radsrv: message authentication failed");
1780         goto errvalauth;
1781     }
1782
1783     if (code == RAD_Status_Server) {
1784         respondstatusserver(rq);
1785         goto exit;
1786     }
1787     
1788     /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1789
1790     if (code == RAD_Accounting_Request) {
1791         memset(newauth, 0, 16);
1792         if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
1793             debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
1794             goto errvalauth;
1795         }
1796     }
1797     
1798     if (rq->from->conf->rewrite) {
1799         dorewrite(rq->buf, rq->from->conf->rewrite);
1800         len = RADLEN(rq->buf) - 20;
1801     }
1802     
1803     attr = attrget(attrs, len, RAD_Attr_User_Name);
1804     if (!attr) {
1805         if (code == RAD_Accounting_Request) {
1806             acclog(attrs, len, rq->from->conf->host);
1807             respondaccounting(rq);
1808         } else
1809             debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1810         goto exit;
1811     }
1812     memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1813     username[ATTRVALLEN(attr)] = '\0';
1814     radattr2ascii(userascii, sizeof(userascii), attr);
1815
1816     if (rq->from->conf->rewriteattrregex) {
1817         if (!rewriteusername(rq, username)) {
1818             debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1819             goto exit;
1820         }
1821         len = RADLEN(rq->buf) - 20;
1822         auth = (uint8_t *)(rq->buf + 4);
1823         attrs = rq->buf + 20;
1824     }
1825
1826     debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
1827     
1828     to = findserver(&realm, username, code == RAD_Accounting_Request);
1829     if (!realm) {
1830         debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1831         goto exit;
1832     }
1833     if (!to) {
1834         if (realm->message && code == RAD_Access_Request) {
1835             debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
1836             respondreject(rq, realm->message);
1837         } else if (realm->accresp && code == RAD_Accounting_Request) {
1838             acclog(attrs, len, rq->from->conf->host);
1839             respondaccounting(rq);
1840         }
1841         goto exit;
1842     }
1843     
1844     if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
1845         debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
1846               rq->from->conf->name, to->conf->name);
1847         goto exit;
1848     }
1849
1850     if (rqinqueue(to, rq->from, id, code)) {
1851         debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
1852               radmsgtype2string(code), rq->from->conf->host, id);
1853         goto exit;
1854     }
1855     
1856     if (code != RAD_Accounting_Request) {
1857         if (!RAND_bytes(newauth, 16)) {
1858             debug(DBG_WARN, "radsrv: failed to generate random auth");
1859             goto exit;
1860         }
1861     }
1862
1863 #ifdef DEBUG
1864     printfchars(NULL, "auth", "%02x ", auth, 16);
1865 #endif
1866
1867     attr = attrget(attrs, len, RAD_Attr_User_Password);
1868     if (attr) {
1869         debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1870         if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
1871             goto exit;
1872     }
1873     
1874     attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1875     if (attr) {
1876         debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1877         if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
1878             goto exit;
1879     }
1880
1881     rq->origid = id;
1882     memcpy(rq->origauth, auth, 16);
1883     memcpy(auth, newauth, 16);
1884     sendrq(to, rq);
1885     return 1;
1886     
1887  exit:
1888     freerqdata(rq);
1889     return 1;
1890
1891  errvalauth:
1892     freerqdata(rq);
1893     return 0;
1894 }
1895
1896 int replyh(struct server *server, unsigned char *buf) {
1897     struct client *from;
1898     struct request *rq;
1899     int i, len, sublen;
1900     unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
1901     struct sockaddr_storage fromsa;
1902     char tmp[760], stationid[760];
1903     
1904     server->connectionok = 1;
1905     server->lostrqs = 0;
1906         
1907     i = buf[1]; /* i is the id */
1908
1909     if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
1910         && *buf != RAD_Accounting_Response) {
1911         debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
1912         return 0;
1913     }
1914     debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
1915
1916     rq = server->requests + i;
1917
1918     pthread_mutex_lock(&server->newrq_mutex);
1919     if (!rq->buf || !rq->tries) {
1920         pthread_mutex_unlock(&server->newrq_mutex);
1921         debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
1922         return 0;
1923     }
1924
1925     if (rq->received) {
1926         pthread_mutex_unlock(&server->newrq_mutex);
1927         debug(DBG_INFO, "replyh: already received, ignoring reply");
1928         return 0;
1929     }
1930         
1931     if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
1932         pthread_mutex_unlock(&server->newrq_mutex);
1933         debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
1934         return 0;
1935     }
1936         
1937     len = RADLEN(buf) - 20;
1938     attrs = buf + 20;
1939
1940     if (!attrvalidate(attrs, len)) {
1941         pthread_mutex_unlock(&server->newrq_mutex);
1942         debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
1943         return 0;
1944     }
1945         
1946     /* Message Authenticator */
1947     messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1948     if (messageauth) {
1949         if (ATTRVALLEN(messageauth) != 16) {
1950             pthread_mutex_unlock(&server->newrq_mutex);
1951             debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
1952             return 0;
1953         }
1954         memcpy(tmp, buf + 4, 16);
1955         memcpy(buf + 4, rq->buf + 4, 16);
1956         if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
1957             pthread_mutex_unlock(&server->newrq_mutex);
1958             debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
1959             return 0;
1960         }
1961         memcpy(buf + 4, tmp, 16);
1962         debug(DBG_DBG, "replyh: message auth ok");
1963     }
1964     
1965     gettimeofday(&server->lastrcv, NULL);
1966     
1967     if (*rq->buf == RAD_Status_Server) {
1968         rq->received = 1;
1969         pthread_mutex_unlock(&server->newrq_mutex);
1970         debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
1971         return 0;
1972     }
1973
1974     gettimeofday(&server->lastreply, NULL);
1975     
1976     from = rq->from;
1977     if (!from) {
1978         pthread_mutex_unlock(&server->newrq_mutex);
1979         debug(DBG_INFO, "replyh: client gone, ignoring reply");
1980         return 0;
1981     }
1982         
1983     if (server->conf->rewrite) {
1984         dorewrite(buf, server->conf->rewrite);
1985         len = RADLEN(buf) - 20;
1986     }
1987     
1988     /* MS MPPE */
1989     for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1990         if (ATTRVALLEN(attr) <= 4)
1991             break;
1992             
1993         if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55)  /* 311 == MS */
1994             continue;
1995             
1996         sublen = ATTRVALLEN(attr) - 4;
1997         subattrs = ATTRVAL(attr) + 4;  
1998         if (!attrvalidate(subattrs, sublen) ||
1999             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2000                     rq, server->conf->secret, from->conf->secret) ||
2001             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2002                     rq, server->conf->secret, from->conf->secret))
2003             break;
2004     }
2005     if (attr) {
2006         pthread_mutex_unlock(&server->newrq_mutex);
2007         debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2008         return 0;
2009     }
2010         
2011     if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2012         attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2013         if (attr) {
2014             radattr2ascii(tmp, sizeof(tmp), attr);
2015             attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2016             if (attr) {
2017                 radattr2ascii(stationid, sizeof(stationid), attr);
2018                 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2019                       radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2020             } else
2021                 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2022         }
2023     }
2024         
2025     buf[1] = (char)rq->origid;
2026     memcpy(buf + 4, rq->origauth, 16);
2027 #ifdef DEBUG    
2028     printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2029 #endif
2030
2031     if (rq->origusername) {
2032         username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2033         if (!username) {
2034             pthread_mutex_unlock(&server->newrq_mutex);
2035             debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2036             return 0;
2037         }
2038         memcpy(username, rq->origusername, strlen(rq->origusername));
2039         len = RADLEN(buf) - 20;
2040         attrs = buf + 20;
2041         if (messageauth)
2042             messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2043     }
2044         
2045     if (messageauth) {
2046         if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2047             pthread_mutex_unlock(&server->newrq_mutex);
2048             debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2049             return 0;
2050         }
2051         debug(DBG_DBG, "replyh: computed messageauthattr");
2052     }
2053
2054     fromsa = rq->fromsa; /* only needed for UDP */
2055     /* once we set received = 1, rq may be reused */
2056     rq->received = 1;
2057
2058     debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2059     sendreply(from, buf, &fromsa, rq->fromudpsock);
2060     pthread_mutex_unlock(&server->newrq_mutex);
2061     return 1;
2062 }
2063
2064 /* code for removing state not finished */
2065 void *clientwr(void *arg) {
2066     struct server *server = (struct server *)arg;
2067     struct request *rq;
2068     pthread_t clientrdth;
2069     int i, dynconffail = 0;
2070     uint8_t rnd;
2071     struct timeval now;
2072     struct timespec timeout;
2073     struct request statsrvrq;
2074     unsigned char statsrvbuf[38];
2075     struct clsrvconf *conf;
2076     
2077     conf = server->conf;
2078     
2079     if (server->dynamiclookuparg && !dynamicconfig(server)) {
2080         dynconffail = 1;
2081         goto errexit;
2082     }
2083     
2084     if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2085         debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2086         goto errexit;
2087     }
2088
2089     memset(&timeout, 0, sizeof(struct timespec));
2090     
2091     if (conf->statusserver) {
2092         memset(&statsrvrq, 0, sizeof(struct request));
2093         memset(statsrvbuf, 0, sizeof(statsrvbuf));
2094         statsrvbuf[0] = RAD_Status_Server;
2095         statsrvbuf[3] = 38;
2096         statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2097         statsrvbuf[21] = 18;
2098         gettimeofday(&server->lastrcv, NULL);
2099     }
2100
2101     if (conf->pdef->connecter) {
2102         if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2103             goto errexit;
2104         server->connectionok = 1;
2105         if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
2106             debug(DBG_ERR, "clientwr: pthread_create failed");
2107             goto errexit;
2108         }
2109     } else
2110         server->connectionok = 1;
2111     
2112     for (;;) {
2113         pthread_mutex_lock(&server->newrq_mutex);
2114         if (!server->newrq) {
2115             gettimeofday(&now, NULL);
2116             /* random 0-7 seconds */
2117             RAND_bytes(&rnd, 1);
2118             rnd /= 32;
2119             if (conf->statusserver) {
2120                 if (!timeout.tv_sec || timeout.tv_sec > server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd)
2121                     timeout.tv_sec = server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd;
2122             } else {
2123                 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2124                     timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2125             }
2126 #if 0       
2127             if (timeout.tv_sec > now.tv_sec)
2128                 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2129 #endif      
2130             pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2131             timeout.tv_sec = 0;
2132         }
2133         if (server->newrq) {
2134             debug(DBG_DBG, "clientwr: got new request");
2135             server->newrq = 0;
2136         }
2137 #if 0   
2138         else
2139             debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2140 #endif  
2141         pthread_mutex_unlock(&server->newrq_mutex);
2142
2143         for (i = 0; i < MAX_REQUESTS; i++) {
2144             if (server->clientrdgone) {
2145                 pthread_join(clientrdth, NULL);
2146                 goto errexit;
2147             }
2148             pthread_mutex_lock(&server->newrq_mutex);
2149             while (i < MAX_REQUESTS && !server->requests[i].buf)
2150                 i++;
2151             if (i == MAX_REQUESTS) {
2152                 pthread_mutex_unlock(&server->newrq_mutex);
2153                 break;
2154             }
2155             rq = server->requests + i;
2156
2157             if (rq->received) {
2158                 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2159                 if (rq->buf) {
2160                     debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2161                     freerqdata(rq);
2162                     /* setting this to NULL means that it can be reused */
2163                     rq->buf = NULL;
2164                 }
2165                 pthread_mutex_unlock(&server->newrq_mutex);
2166                 continue;
2167             }
2168             
2169             gettimeofday(&now, NULL);
2170             if (now.tv_sec < rq->expiry.tv_sec) {
2171                 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2172                     timeout.tv_sec = rq->expiry.tv_sec;
2173                 pthread_mutex_unlock(&server->newrq_mutex);
2174                 continue;
2175             }
2176
2177             if (rq->tries == (*rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2178                 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2179                 if (conf->statusserver) {
2180                     if (*rq->buf == RAD_Status_Server) {
2181                         debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2182                         if (server->lostrqs < 255)
2183                             server->lostrqs++;
2184                     }
2185                 } else {
2186                     debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2187                     if (server->lostrqs < 255)
2188                         server->lostrqs++;
2189                 }
2190                 freerqdata(rq);
2191                 /* setting this to NULL means that it can be reused */
2192                 rq->buf = NULL;
2193                 pthread_mutex_unlock(&server->newrq_mutex);
2194                 continue;
2195             }
2196             pthread_mutex_unlock(&server->newrq_mutex);
2197
2198             rq->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2199             if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2200                 timeout.tv_sec = rq->expiry.tv_sec;
2201             rq->tries++;
2202             conf->pdef->clientradput(server, server->requests[i].buf);
2203         }
2204         if (conf->statusserver) {
2205             gettimeofday(&now, NULL);
2206             if (now.tv_sec - server->lastrcv.tv_sec >= STATUS_SERVER_PERIOD) {
2207                 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2208                     debug(DBG_WARN, "clientwr: failed to generate random auth");
2209                     continue;
2210                 }
2211                 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2212                 if (!statsrvrq.buf) {
2213                     debug(DBG_ERR, "clientwr: malloc failed");
2214                     continue;
2215                 }
2216                 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2217                 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2218                 sendrq(server, &statsrvrq);
2219             }
2220         }
2221     }
2222  errexit:
2223     conf->servers = NULL;
2224     if (server->dynamiclookuparg) {
2225         removeserversubrealms(realms, conf);
2226         if (dynconffail)
2227             free(conf);
2228         else
2229             freeclsrvconf(conf);
2230     }
2231     freeserver(server, 1);
2232     ERR_remove_state(0);
2233     return NULL;
2234 }
2235
2236 void createlistener(uint8_t type, char *arg) {
2237     pthread_t th;
2238     struct clsrvconf *listenres;
2239     struct addrinfo *res;
2240     int s = -1, on = 1, *sp = NULL;
2241     
2242     listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2243     if (!listenres)
2244         debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2245     
2246     for (res = listenres->addrinfo; res; res = res->ai_next) {
2247         s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2248         if (s < 0) {
2249             debug(DBG_WARN, "createlistener: socket failed");
2250             continue;
2251         }
2252         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2253 #ifdef IPV6_V6ONLY
2254         if (res->ai_family == AF_INET6)
2255             setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2256 #endif          
2257         if (bind(s, res->ai_addr, res->ai_addrlen)) {
2258             debug(DBG_WARN, "createlistener: bind failed");
2259             close(s);
2260             s = -1;
2261             continue;
2262         }
2263
2264         sp = malloc(sizeof(int));
2265         if (!sp)
2266             debugx(1, DBG_ERR, "malloc failed");
2267         *sp = s;
2268         if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
2269             debugx(1, DBG_ERR, "pthread_create failed");
2270         pthread_detach(th);
2271     }
2272     if (!sp)
2273         debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2274     
2275     debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
2276           listenres->host ? listenres->host : "*", listenres->port);
2277     freeclsrvres(listenres);
2278 }
2279
2280 void createlisteners(uint8_t type, char **args) {
2281     int i;
2282
2283     if (args)
2284         for (i = 0; args[i]; i++)
2285             createlistener(type, args[i]);
2286     else
2287         createlistener(type, NULL);
2288 }
2289
2290 #ifdef DEBUG
2291 void ssl_info_callback(const SSL *ssl, int where, int ret) {
2292     const char *s;
2293     int w;
2294
2295     w = where & ~SSL_ST_MASK;
2296
2297     if (w & SSL_ST_CONNECT)
2298         s = "SSL_connect";
2299     else if (w & SSL_ST_ACCEPT)
2300         s = "SSL_accept";
2301     else
2302         s = "undefined";
2303
2304     if (where & SSL_CB_LOOP)
2305         debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
2306     else if (where & SSL_CB_ALERT) {
2307         s = (where & SSL_CB_READ) ? "read" : "write";
2308         debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
2309     }
2310     else if (where & SSL_CB_EXIT) {
2311         if (ret == 0)
2312             debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
2313         else if (ret < 0)
2314             debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
2315     }
2316 }
2317 #endif
2318
2319 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2320     SSL_CTX *ctx = NULL;
2321     STACK_OF(X509_NAME) *calist;
2322     X509_STORE *x509_s;
2323     int i;
2324     unsigned long error;
2325
2326     if (!ssl_locks) {
2327         ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2328         ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2329         for (i = 0; i < CRYPTO_num_locks(); i++) {
2330             ssl_lock_count[i] = 0;
2331             pthread_mutex_init(&ssl_locks[i], NULL);
2332         }
2333         CRYPTO_set_id_callback(ssl_thread_id);
2334         CRYPTO_set_locking_callback(ssl_locking_callback);
2335
2336         SSL_load_error_strings();
2337         SSL_library_init();
2338
2339         while (!RAND_status()) {
2340             time_t t = time(NULL);
2341             pid_t pid = getpid();
2342             RAND_seed((unsigned char *)&t, sizeof(time_t));
2343             RAND_seed((unsigned char *)&pid, sizeof(pid));
2344         }
2345     }
2346
2347     switch (type) {
2348     case RAD_TLS:
2349         ctx = SSL_CTX_new(TLSv1_method());
2350 #ifdef DEBUG    
2351         SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2352 #endif  
2353         break;
2354     case RAD_DTLS:
2355         ctx = SSL_CTX_new(DTLSv1_method());
2356 #ifdef DEBUG    
2357         SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2358 #endif  
2359         SSL_CTX_set_read_ahead(ctx, 1);
2360         break;
2361     }
2362     if (!ctx) {
2363         debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2364         return NULL;
2365     }
2366     
2367     if (conf->certkeypwd) {
2368         SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2369         SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2370     }
2371     if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2372         !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2373         !SSL_CTX_check_private_key(ctx) ||
2374         !SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2375         while ((error = ERR_get_error()))
2376             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2377         debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2378         SSL_CTX_free(ctx);
2379         return NULL;
2380     }
2381
2382     calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2383     if (!conf->cacertfile || calist) {
2384         if (conf->cacertpath) {
2385             if (!calist)
2386                 calist = sk_X509_NAME_new_null();
2387             if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2388                 sk_X509_NAME_free(calist);
2389                 calist = NULL;
2390             }
2391         }
2392     }
2393     if (!calist) {
2394         while ((error = ERR_get_error()))
2395             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2396         debug(DBG_ERR, "tlscreatectx: Error adding CA subjects in TLS context %s", conf->name);
2397         SSL_CTX_free(ctx);
2398         return NULL;
2399     }
2400     ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2401     SSL_CTX_set_client_CA_list(ctx, calist);
2402     
2403     SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2404     SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2405
2406     if (conf->crlcheck) {
2407         x509_s = SSL_CTX_get_cert_store(ctx);
2408         X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2409     }
2410
2411     debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
2412     return ctx;
2413 }
2414
2415 SSL_CTX *tlsgetctx(uint8_t type, char *alt1, char *alt2) {
2416     struct list_node *entry;
2417     struct tls *t, *t1 = NULL, *t2 = NULL;
2418     SSL_CTX *ctx = NULL;
2419     
2420     pthread_mutex_lock(&tlsconfs_lock);
2421     
2422     for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2423         t = (struct tls *)entry->data;
2424         if (!strcasecmp(t->name, alt1)) {
2425             t1 = t;
2426             break;
2427         }
2428         if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2429             t2 = t;
2430     }
2431
2432     t = (t1 ? t1 : t2);
2433     if (!t)
2434         goto exit;
2435
2436     switch (type) {
2437     case RAD_TLS:
2438         if (!t->tlsctx)
2439             t->tlsctx = tlscreatectx(RAD_TLS, t);
2440         ctx = t->tlsctx;
2441         break;
2442     case RAD_DTLS:
2443         if (!t->dtlsctx)
2444             t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2445         ctx = t->dtlsctx;
2446         break;
2447     }
2448     
2449  exit:
2450     pthread_mutex_unlock(&tlsconfs_lock);
2451     return ctx;
2452 }
2453
2454 struct list *addsrvconfs(char *value, char **names) {
2455     struct list *conflist;
2456     int n;
2457     struct list_node *entry;
2458     struct clsrvconf *conf = NULL;
2459     
2460     if (!names || !*names)
2461         return NULL;
2462     
2463     conflist = list_create();
2464     if (!conflist) {
2465         debug(DBG_ERR, "malloc failed");
2466         return NULL;
2467     }
2468
2469     for (n = 0; names[n]; n++) {
2470         for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2471             conf = (struct clsrvconf *)entry->data;
2472             if (!strcasecmp(names[n], conf->name))
2473                 break;
2474         }
2475         if (!entry) {
2476             debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2477             list_destroy(conflist);
2478             return NULL;
2479         }
2480         if (!list_push(conflist, conf)) {
2481             debug(DBG_ERR, "malloc failed");
2482             list_destroy(conflist);
2483             return NULL;
2484         }
2485         debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2486     }
2487     return conflist;
2488 }
2489
2490 void freerealm(struct realm *realm) {
2491     if (!realm)
2492         return;
2493     free(realm->name);
2494     free(realm->message);
2495     regfree(&realm->regex);
2496     pthread_mutex_destroy(&realm->subrealms_mutex);
2497     if (realm->subrealms)
2498         list_destroy(realm->subrealms);
2499     if (realm->srvconfs) {
2500         /* emptying list without freeing data */
2501         while (list_shift(realm->srvconfs));
2502         list_destroy(realm->srvconfs);
2503     }
2504     if (realm->accsrvconfs) {
2505         /* emptying list without freeing data */
2506         while (list_shift(realm->accsrvconfs));
2507         list_destroy(realm->accsrvconfs);
2508     }
2509     free(realm);
2510 }
2511
2512 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2513     int n;
2514     struct realm *realm;
2515     char *s, *regex = NULL;
2516     
2517     if (*value == '/') {
2518         /* regexp, remove optional trailing / if present */
2519         if (value[strlen(value) - 1] == '/')
2520             value[strlen(value) - 1] = '\0';
2521     } else {
2522         /* not a regexp, let us make it one */
2523         if (*value == '*' && !value[1])
2524             regex = stringcopy(".*", 0);
2525         else {
2526             for (n = 0, s = value; *s;)
2527                 if (*s++ == '.')
2528                     n++;
2529             regex = malloc(strlen(value) + n + 3);
2530             if (regex) {
2531                 regex[0] = '@';
2532                 for (n = 1, s = value; *s; s++) {
2533                     if (*s == '.')
2534                         regex[n++] = '\\';
2535                     regex[n++] = *s;
2536                 }
2537                 regex[n++] = '$';
2538                 regex[n] = '\0';
2539             }
2540         }
2541         if (!regex) {
2542             debug(DBG_ERR, "malloc failed");
2543             realm = NULL;
2544             goto exit;
2545         }
2546         debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2547     }
2548
2549     realm = malloc(sizeof(struct realm));
2550     if (!realm) {
2551         debug(DBG_ERR, "malloc failed");
2552         goto exit;
2553     }
2554     memset(realm, 0, sizeof(struct realm));
2555     
2556     if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
2557         debug(DBG_ERR, "mutex init failed");
2558         free(realm);
2559         realm = NULL;
2560         goto exit;
2561     }
2562
2563     realm->name = stringcopy(value, 0);
2564     if (!realm->name) {
2565         debug(DBG_ERR, "malloc failed");
2566         goto errexit;
2567     }
2568     if (message && strlen(message) > 253) {
2569         debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2570         goto errexit;
2571     }
2572     realm->message = message;
2573     realm->accresp = accresp;
2574     
2575     if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
2576         debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2577         goto errexit;
2578     }
2579     
2580     if (servers && *servers) {
2581         realm->srvconfs = addsrvconfs(value, servers);
2582         if (!realm->srvconfs)
2583             goto errexit;
2584     }
2585     
2586     if (accservers && *accservers) {
2587         realm->accsrvconfs = addsrvconfs(value, accservers);
2588         if (!realm->accsrvconfs)
2589             goto errexit;
2590     }
2591
2592     if (!list_push(realmlist, realm)) {
2593         debug(DBG_ERR, "malloc failed");
2594         pthread_mutex_destroy(&realm->subrealms_mutex);
2595         goto errexit;
2596     }
2597     
2598     debug(DBG_DBG, "addrealm: added realm %s", value);
2599     goto exit;
2600
2601  errexit:
2602     freerealm(realm);
2603     realm = NULL;
2604     
2605  exit:
2606     free(regex);
2607     if (servers) {
2608         for (n = 0; servers[n]; n++)
2609             free(servers[n]);
2610         free(servers);
2611     }
2612     if (accservers) {
2613         for (n = 0; accservers[n]; n++)
2614             free(accservers[n]);
2615         free(accservers);
2616     }
2617     return realm;
2618 }
2619
2620 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2621     struct clsrvconf *srvconf;
2622     struct realm *newrealm = NULL;
2623     char *realmname, *s;
2624     pthread_t clientth;
2625     
2626     if (!conf->dynamiclookupcommand)
2627         return;
2628
2629     /* create dynamic for the realm (string after last @, exit if nothing after @ */
2630     realmname = strrchr(id, '@');
2631     if (!realmname)
2632         return;
2633     realmname++;
2634     if (!*realmname)
2635         return;
2636     for (s = realmname; *s; s++)
2637         if (*s != '.' && *s != '-' && !isalnum((int)*s))
2638             return;
2639     
2640     pthread_mutex_lock(&realm->subrealms_mutex);
2641     /* exit if we now already got a matching subrealm */
2642     if (id2realm(realm->subrealms, id))
2643         goto exit;
2644     srvconf = malloc(sizeof(struct clsrvconf));
2645     if (!srvconf) {
2646         debug(DBG_ERR, "malloc failed");
2647         goto exit;
2648     }
2649     *srvconf = *conf;
2650     if (!addserver(srvconf))
2651         goto errexit;
2652
2653     if (!realm->subrealms)
2654         realm->subrealms = list_create();
2655     if (!realm->subrealms)
2656         goto errexit;
2657     newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2658     if (!newrealm)
2659         goto errexit;
2660
2661     /* add server and accserver to newrealm */
2662     newrealm->srvconfs = list_create();
2663     if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2664         debug(DBG_ERR, "malloc failed");
2665         goto errexit;
2666     }
2667     newrealm->accsrvconfs = list_create();
2668     if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2669         debug(DBG_ERR, "malloc failed");
2670         goto errexit;
2671     }
2672
2673     srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2674
2675     if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2676         debug(DBG_ERR, "pthread_create failed");
2677         goto errexit;
2678     }
2679     pthread_detach(clientth);
2680     goto exit;
2681     
2682  errexit:
2683     if (newrealm) {
2684         list_removedata(realm->subrealms, newrealm);
2685         freerealm(newrealm);
2686         if (!list_first(realm->subrealms)) {
2687             list_destroy(realm->subrealms);
2688             realm->subrealms = NULL;
2689         }
2690     }
2691     freeserver(srvconf->servers, 1);
2692     free(srvconf);
2693     debug(DBG_ERR, "failed to create dynamic server");
2694
2695  exit:
2696     pthread_mutex_unlock(&realm->subrealms_mutex);
2697 }
2698
2699 int dynamicconfig(struct server *server) {
2700     int ok, fd[2], status;
2701     pid_t pid;
2702     struct clsrvconf *conf = server->conf;
2703     struct gconffile *cf = NULL;
2704     
2705     /* for now we only learn hostname/address */
2706     debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2707
2708     if (pipe(fd) > 0) {
2709         debug(DBG_ERR, "dynamicconfig: pipe error");
2710         goto errexit;
2711     }
2712     pid = fork();
2713     if (pid < 0) {
2714         debug(DBG_ERR, "dynamicconfig: fork error");
2715         close(fd[0]);
2716         close(fd[1]);
2717         goto errexit;
2718     } else if (pid == 0) {
2719         /* child */
2720         close(fd[0]);
2721         if (fd[1] != STDOUT_FILENO) {
2722             if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2723                 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2724             close(fd[1]);
2725         }
2726         if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2727             debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2728     }
2729
2730     close(fd[1]);
2731     pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2732     ok = getgenericconfig(&cf, NULL,
2733                           "Server", CONF_CBK, confserver_cb, (void *)conf,
2734                           NULL
2735                           );
2736     freegconf(&cf);
2737         
2738     if (waitpid(pid, &status, 0) < 0) {
2739         debug(DBG_ERR, "dynamicconfig: wait error");
2740         goto errexit;
2741     }
2742     
2743     if (status) {
2744         debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2745         goto errexit;
2746     }
2747
2748     if (ok)
2749         return 1;
2750
2751  errexit:    
2752     debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2753     return 0;
2754 }
2755
2756 int addmatchcertattr(struct clsrvconf *conf) {
2757     char *v;
2758     regex_t **r;
2759     
2760     if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2761         r = &conf->certcnregex;
2762         v = conf->matchcertattr + 4;
2763     } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2764         r = &conf->certuriregex;
2765         v = conf->matchcertattr + 20;
2766     } else
2767         return 0;
2768     if (!*v)
2769         return 0;
2770     /* regexp, remove optional trailing / if present */
2771     if (v[strlen(v) - 1] == '/')
2772         v[strlen(v) - 1] = '\0';
2773     if (!*v)
2774         return 0;
2775
2776     *r = malloc(sizeof(regex_t));
2777     if (!*r) {
2778         debug(DBG_ERR, "malloc failed");
2779         return 0;
2780     }
2781     if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
2782         free(*r);
2783         *r = NULL;
2784         debug(DBG_ERR, "failed to compile regular expression %s", v);
2785         return 0;
2786     }
2787     return 1;
2788 }
2789
2790 int addrewriteattr(struct clsrvconf *conf) {
2791     char *v, *w;
2792     
2793     v = conf->rewriteattr + 11;
2794     if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
2795         return 0;
2796     /* regexp, remove optional trailing / if present */
2797     if (v[strlen(v) - 1] == '/')
2798         v[strlen(v) - 1] = '\0';
2799
2800     w = strchr(v, '/');
2801     if (!*w)
2802         return 0;
2803     *w = '\0';
2804     w++;
2805     
2806     conf->rewriteattrregex = malloc(sizeof(regex_t));
2807     if (!conf->rewriteattrregex) {
2808         debug(DBG_ERR, "malloc failed");
2809         return 0;
2810     }
2811
2812     conf->rewriteattrreplacement = stringcopy(w, 0);
2813     if (!conf->rewriteattrreplacement) {
2814         free(conf->rewriteattrregex);
2815         conf->rewriteattrregex = NULL;
2816         return 0;
2817     }
2818     
2819     if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
2820         free(conf->rewriteattrregex);
2821         conf->rewriteattrregex = NULL;
2822         free(conf->rewriteattrreplacement);
2823         conf->rewriteattrreplacement = NULL;
2824         debug(DBG_ERR, "failed to compile regular expression %s", v);
2825         return 0;
2826     }
2827
2828     return 1;
2829 }
2830
2831 /* should accept both names and numeric values, only numeric right now */
2832 uint8_t attrname2val(char *attrname) {
2833     int val = 0;
2834     
2835     val = atoi(attrname);
2836     return val > 0 && val < 256 ? val : 0;
2837 }
2838
2839 /* should accept both names and numeric values, only numeric right now */
2840 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2841     char *s;
2842     
2843     *vendor = atoi(attrname);
2844     s = strchr(attrname, ':');
2845     if (!s) {
2846         *type = -1;
2847         return 1;
2848     }
2849     *type = atoi(s + 1);
2850     return *type >= 0 && *type < 256;
2851 }
2852
2853 struct rewrite *getrewrite(char *alt1, char *alt2) {
2854     struct list_node *entry;
2855     struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
2856     
2857     for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
2858         r = (struct rewriteconf *)entry->data;
2859         if (!strcasecmp(r->name, alt1)) {
2860             r1 = r;
2861             break;
2862         }
2863         if (!r2 && alt2 && !strcasecmp(r->name, alt2))
2864             r2 = r;
2865     }
2866
2867     r = (r1 ? r1 : r2);
2868     if (!r)
2869         return NULL;
2870     return r->rewrite;
2871 }
2872
2873 void addrewrite(char *value, char **attrs, char **vattrs) {
2874     struct rewriteconf *new;
2875     struct rewrite *rewrite = NULL;
2876     int i, n;
2877     uint8_t *a = NULL;
2878     uint32_t *p, *va = NULL;
2879
2880     if (attrs) {
2881         n = 0;
2882         for (; attrs[n]; n++);
2883         a = malloc((n + 1) * sizeof(uint8_t));
2884         if (!a)
2885             debugx(1, DBG_ERR, "malloc failed");
2886     
2887         for (i = 0; i < n; i++) {
2888             if (!(a[i] = attrname2val(attrs[i])))
2889                 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
2890             free(attrs[i]);
2891         }
2892         free(attrs);
2893         a[i] = 0;
2894     }
2895     
2896     if (vattrs) {
2897         n = 0;
2898         for (; vattrs[n]; n++);
2899         va = malloc((2 * n + 1) * sizeof(uint32_t));
2900         if (!va)
2901             debugx(1, DBG_ERR, "malloc failed");
2902     
2903         for (p = va, i = 0; i < n; i++, p += 2) {
2904             if (!vattrname2val(vattrs[i], p, p + 1))
2905                 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
2906             free(vattrs[i]);
2907         }
2908         free(vattrs);
2909         *p = 0;
2910     }
2911     
2912     if (a || va) {
2913         rewrite = malloc(sizeof(struct rewrite));
2914         if (!rewrite)
2915             debugx(1, DBG_ERR, "malloc failed");
2916         rewrite->removeattrs = a;
2917         rewrite->removevendorattrs = va;
2918     }
2919     
2920     new = malloc(sizeof(struct rewriteconf));
2921     if (!new || !list_push(rewriteconfs, new))
2922         debugx(1, DBG_ERR, "malloc failed");
2923
2924     memset(new, 0, sizeof(struct rewriteconf));
2925     new->name = stringcopy(value, 0);
2926     if (!new->name)
2927         debugx(1, DBG_ERR, "malloc failed");
2928         
2929     new->rewrite = rewrite;
2930     debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2931 }
2932
2933 void freeclsrvconf(struct clsrvconf *conf) {
2934     free(conf->name);
2935     free(conf->host);
2936     free(conf->port);
2937     free(conf->secret);
2938     free(conf->tls);
2939     free(conf->matchcertattr);
2940     if (conf->certcnregex)
2941         regfree(conf->certcnregex);
2942     if (conf->certuriregex)
2943         regfree(conf->certuriregex);
2944     free(conf->confrewrite);
2945     free(conf->rewriteattr);
2946     if (conf->rewriteattrregex)
2947         regfree(conf->rewriteattrregex);
2948     free(conf->rewriteattrreplacement);
2949     free(conf->dynamiclookupcommand);
2950     free(conf->rewrite);
2951     if (conf->addrinfo)
2952         freeaddrinfo(conf->addrinfo);
2953     /* not touching ssl_ctx, clients and servers */
2954     free(conf);
2955 }
2956
2957 int mergeconfstring(char **dst, char **src) {
2958     char *t;
2959     
2960     if (*src) {
2961         *dst = *src;
2962         *src = NULL;
2963         return 1;
2964     }
2965     if (*dst) {
2966         t = stringcopy(*dst, 0);
2967         if (!t) {
2968             debug(DBG_ERR, "malloc failed");
2969             return 0;
2970         }
2971         *dst = t;
2972     }
2973     return 1;
2974 }
2975
2976 /* assumes dst is a shallow copy */
2977 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2978     if (!mergeconfstring(&dst->name, &src->name) ||
2979         !mergeconfstring(&dst->host, &src->host) ||
2980         !mergeconfstring(&dst->port, &src->port) ||
2981         !mergeconfstring(&dst->secret, &src->secret) ||
2982         !mergeconfstring(&dst->tls, &src->tls) ||
2983         !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2984         !mergeconfstring(&dst->confrewrite, &src->confrewrite) ||
2985         !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
2986         return 0;
2987     if (src->pdef)
2988         dst->pdef = src->pdef;
2989     dst->statusserver = src->statusserver;
2990     dst->certnamecheck = src->certnamecheck;
2991     if (src->retryinterval != 255)
2992         dst->retryinterval = src->retryinterval;
2993     if (src->retrycount != 255)
2994         dst->retrycount = src->retrycount;
2995     return 1;
2996 }
2997
2998 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2999     struct clsrvconf *conf;
3000     char *conftype = NULL;
3001     
3002     debug(DBG_DBG, "confclient_cb called for %s", block);
3003
3004     conf = malloc(sizeof(struct clsrvconf));
3005     if (!conf || !list_push(clconfs, conf))
3006         debugx(1, DBG_ERR, "malloc failed");
3007     memset(conf, 0, sizeof(struct clsrvconf));
3008     conf->certnamecheck = 1;
3009     
3010     if (!getgenericconfig(cf, block,
3011                      "type", CONF_STR, &conftype,
3012                      "host", CONF_STR, &conf->host,
3013                      "secret", CONF_STR, &conf->secret,
3014                      "tls", CONF_STR, &conf->tls,
3015                      "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3016                      "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3017                      "rewrite", CONF_STR, &conf->confrewrite,
3018                      "rewriteattribute", CONF_STR, &conf->rewriteattr,
3019                      NULL
3020                           ))
3021         debugx(1, DBG_ERR, "configuration error");
3022     
3023     conf->name = stringcopy(val, 0);
3024     if (!conf->host)
3025         conf->host = stringcopy(val, 0);
3026     if (!conf->name || !conf->host)
3027         debugx(1, DBG_ERR, "malloc failed");
3028         
3029     if (!conftype)
3030         debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3031     conf->type = protoname2int(conftype);
3032     conf->pdef = &protodefs[conf->type];
3033     if (!conf->pdef->name)
3034         debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3035     free(conftype);
3036     
3037     if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3038         conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultclient", "default");
3039         if (!conf->ssl_ctx)
3040             debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3041         if (conf->matchcertattr && !addmatchcertattr(conf))
3042             debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3043     }
3044     
3045     conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
3046     
3047     if (conf->rewriteattr) {
3048         if (!addrewriteattr(conf))
3049             debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3050     }
3051     
3052     if (!resolvepeer(conf, 0))
3053         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3054     
3055     if (!conf->secret) {
3056         if (!conf->pdef->secretdefault)
3057             debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3058         conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3059         if (!conf->secret)
3060             debugx(1, DBG_ERR, "malloc failed");
3061     }
3062     return 1;
3063 }
3064
3065 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3066     if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3067         conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultserver", "default");
3068         if (!conf->ssl_ctx) {
3069             debug(DBG_ERR, "error in block %s, no tls context defined", block);
3070             return 0;
3071         }
3072         if (conf->matchcertattr && !addmatchcertattr(conf)) {
3073             debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3074             return 0;
3075         }
3076     }
3077
3078     if (!conf->port) {
3079         conf->port = stringcopy(conf->pdef->portdefault, 0);
3080         if (!conf->port) {
3081             debug(DBG_ERR, "malloc failed");
3082             return 0;
3083         }
3084     }
3085     
3086     if (conf->retryinterval == 255)
3087         conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3088     if (conf->retrycount == 255)
3089         conf->retrycount = protodefs[conf->type].retrycountdefault;
3090     
3091     conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
3092
3093     if (!conf->secret) {
3094         if (!conf->pdef->secretdefault) {
3095             debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3096             return 0;
3097         }
3098         conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3099         if (!conf->secret) {
3100             debug(DBG_ERR, "malloc failed");
3101             return 0;
3102         }
3103     }
3104     
3105     if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3106         debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3107         return 0;
3108     }
3109     return 1;
3110 }
3111                         
3112 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3113     struct clsrvconf *conf, *resconf;
3114     char *conftype = NULL;
3115     long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3116     
3117     debug(DBG_DBG, "confserver_cb called for %s", block);
3118
3119     conf = malloc(sizeof(struct clsrvconf));
3120     if (!conf) {
3121         debug(DBG_ERR, "malloc failed");
3122         return 0;
3123     }
3124     memset(conf, 0, sizeof(struct clsrvconf));
3125     resconf = (struct clsrvconf *)arg;
3126     if (resconf) {
3127         conf->statusserver = resconf->statusserver;
3128         conf->certnamecheck = resconf->certnamecheck;
3129     } else
3130         conf->certnamecheck = 1;
3131
3132     if (!getgenericconfig(cf, block,
3133                           "type", CONF_STR, &conftype,
3134                           "host", CONF_STR, &conf->host,
3135                           "port", CONF_STR, &conf->port,
3136                           "secret", CONF_STR, &conf->secret,
3137                           "tls", CONF_STR, &conf->tls,
3138                           "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3139                           "rewrite", CONF_STR, &conf->confrewrite,
3140                           "StatusServer", CONF_BLN, &conf->statusserver,
3141                           "RetryInterval", CONF_LINT, &retryinterval,
3142                           "RetryCount", CONF_LINT, &retrycount,
3143                           "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3144                           "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3145                           NULL
3146                           )) {
3147         debug(DBG_ERR, "configuration error");
3148         goto errexit;
3149     }
3150     
3151     conf->name = stringcopy(val, 0);
3152     if (!conf->name) {
3153         debug(DBG_ERR, "malloc failed");
3154         goto errexit;
3155     }
3156     if (!conf->host) {
3157         conf->host = stringcopy(val, 0);
3158         if (!conf->host) {
3159             debug(DBG_ERR, "malloc failed");
3160             goto errexit;
3161         }
3162     }
3163
3164     if (!conftype)
3165         debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3166     conf->type = protoname2int(conftype);
3167     conf->pdef = &protodefs[conf->type];
3168     if (!conf->pdef->name) {
3169         debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3170         free(conftype);
3171         goto errexit;
3172     }
3173     free(conftype);
3174             
3175     if (retryinterval != LONG_MIN) {
3176         if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3177             debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3178             goto errexit;
3179         }
3180         conf->retryinterval = (uint8_t)retryinterval;
3181     } else
3182         conf->retryinterval = 255;
3183     
3184     if (retrycount != LONG_MIN) {
3185         if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3186             debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3187             goto errexit;
3188         }
3189         conf->retrycount = (uint8_t)retrycount;
3190     } else
3191         conf->retrycount = 255;
3192     
3193     if (resconf) {
3194         if (!mergesrvconf(resconf, conf))
3195             goto errexit;
3196         free(conf);
3197         conf = resconf;
3198         if (conf->dynamiclookupcommand) {
3199             free(conf->dynamiclookupcommand);
3200             conf->dynamiclookupcommand = NULL;
3201         }
3202     }
3203
3204     if (resconf || !conf->dynamiclookupcommand) {
3205         if (!compileserverconfig(conf, block))
3206             goto errexit;
3207     }
3208     
3209     if (resconf)
3210         return 1;
3211         
3212     if (!list_push(srvconfs, conf)) {
3213         debug(DBG_ERR, "malloc failed");
3214         goto errexit;
3215     }
3216     return 1;
3217
3218  errexit:    
3219     freeclsrvconf(conf);
3220     return 0;
3221 }
3222
3223 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3224     char **servers = NULL, **accservers = NULL, *msg = NULL;
3225     uint8_t accresp = 0;
3226     
3227     debug(DBG_DBG, "confrealm_cb called for %s", block);
3228     
3229     if (!getgenericconfig(cf, block,
3230                      "server", CONF_MSTR, &servers,
3231                      "accountingServer", CONF_MSTR, &accservers,
3232                      "ReplyMessage", CONF_STR, &msg,
3233                      "AccountingResponse", CONF_BLN, &accresp,
3234                      NULL
3235                           ))
3236         debugx(1, DBG_ERR, "configuration error");
3237
3238     addrealm(realms, val, servers, accservers, msg, accresp);
3239     return 1;
3240 }
3241
3242 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3243     struct tls *conf;
3244     
3245     debug(DBG_DBG, "conftls_cb called for %s", block);
3246     
3247     conf = malloc(sizeof(struct tls));
3248     if (!conf) {
3249         debug(DBG_ERR, "conftls_cb: malloc failed");
3250         return 0;
3251     }
3252     memset(conf, 0, sizeof(struct tls));
3253     
3254     if (!getgenericconfig(cf, block,
3255                      "CACertificateFile", CONF_STR, &conf->cacertfile,
3256                      "CACertificatePath", CONF_STR, &conf->cacertpath,
3257                      "CertificateFile", CONF_STR, &conf->certfile,
3258                      "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3259                      "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3260                      "CRLCheck", CONF_BLN, &conf->crlcheck,
3261                      NULL
3262                           )) {
3263         debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3264         goto errexit;
3265     }
3266     if (!conf->certfile || !conf->certkeyfile) {
3267         debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3268         goto errexit;
3269     }
3270     if (!conf->cacertfile && !conf->cacertpath) {
3271         debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3272         goto errexit;
3273     }
3274
3275     conf->name = stringcopy(val, 0);
3276     if (!conf->name) {
3277         debug(DBG_ERR, "conftls_cb: malloc failed");
3278         goto errexit;
3279     }
3280     
3281     pthread_mutex_lock(&tlsconfs_lock);
3282     if (!list_push(tlsconfs, conf)) {
3283         debug(DBG_ERR, "conftls_cb: malloc failed");
3284         pthread_mutex_unlock(&tlsconfs_lock);
3285         goto errexit;
3286     }
3287     pthread_mutex_unlock(&tlsconfs_lock);
3288             
3289     debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3290     return 1;
3291
3292  errexit:
3293     free(conf->cacertfile);
3294     free(conf->cacertpath);
3295     free(conf->certfile);
3296     free(conf->certkeyfile);
3297     free(conf->certkeypwd);
3298     free(conf);
3299     return 0;
3300 }
3301
3302 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3303     char **attrs = NULL, **vattrs = NULL;
3304     
3305     debug(DBG_DBG, "confrewrite_cb called for %s", block);
3306     
3307     if (!getgenericconfig(cf, block,
3308                      "removeAttribute", CONF_MSTR, &attrs,
3309                      "removeVendorAttribute", CONF_MSTR, &vattrs,
3310                      NULL
3311                           ))
3312         debugx(1, DBG_ERR, "configuration error");
3313     addrewrite(val, attrs, vattrs);
3314     return 1;
3315 }
3316
3317 void getmainconfig(const char *configfile) {
3318     long int loglevel = LONG_MIN;
3319     struct gconffile *cfs;
3320
3321     cfs = openconfigfile(configfile);
3322     memset(&options, 0, sizeof(options));
3323     
3324     clconfs = list_create();
3325     if (!clconfs)
3326         debugx(1, DBG_ERR, "malloc failed");
3327     
3328     srvconfs = list_create();
3329     if (!srvconfs)
3330         debugx(1, DBG_ERR, "malloc failed");
3331     
3332     realms = list_create();
3333     if (!realms)
3334         debugx(1, DBG_ERR, "malloc failed");    
3335  
3336     tlsconfs = list_create();
3337     if (!tlsconfs)
3338         debugx(1, DBG_ERR, "malloc failed");
3339     
3340     rewriteconfs = list_create();
3341     if (!rewriteconfs)
3342         debugx(1, DBG_ERR, "malloc failed");    
3343  
3344     if (!getgenericconfig(&cfs, NULL,
3345                           "ListenUDP", CONF_MSTR, &options.listenudp,
3346                           "ListenTCP", CONF_MSTR, &options.listentcp,
3347                           "ListenTLS", CONF_MSTR, &options.listentls,
3348                           "ListenDTLS", CONF_MSTR, &options.listendtls,
3349                           "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
3350                           "SourceUDP", CONF_STR, &options.sourceudp,
3351                           "SourceTCP", CONF_STR, &options.sourcetcp,
3352                           "SourceTLS", CONF_STR, &options.sourcetls,
3353                           "SourceDTLS", CONF_STR, &options.sourcedtls,
3354                           "LogLevel", CONF_LINT, &loglevel,
3355                           "LogDestination", CONF_STR, &options.logdestination,
3356                           "LoopPrevention", CONF_BLN, &options.loopprevention,
3357                           "Client", CONF_CBK, confclient_cb, NULL,
3358                           "Server", CONF_CBK, confserver_cb, NULL,
3359                           "Realm", CONF_CBK, confrealm_cb, NULL,
3360                           "TLS", CONF_CBK, conftls_cb, NULL,
3361                           "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3362                           NULL
3363                           ))
3364         debugx(1, DBG_ERR, "configuration error");
3365     
3366     if (loglevel != LONG_MIN) {
3367         if (loglevel < 1 || loglevel > 4)
3368             debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3369         options.loglevel = (uint8_t)loglevel;
3370     }
3371 }
3372
3373 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3374     int c;
3375
3376     while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3377         switch (c) {
3378         case 'c':
3379             *configfile = optarg;
3380             break;
3381         case 'd':
3382             if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3383                 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3384             *loglevel = *optarg - '0';
3385             break;
3386         case 'f':
3387             *foreground = 1;
3388             break;
3389         case 'p':
3390             *pretend = 1;
3391             break;
3392         case 'v':
3393                 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3394         default:
3395             goto usage;
3396         }
3397     }
3398     if (!(argc - optind))
3399         return;
3400
3401  usage:
3402     debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3403 }
3404
3405 #ifdef SYS_SOLARIS9
3406 int daemon(int a, int b) {
3407     int i;
3408
3409     if (fork())
3410         exit(0);
3411
3412     setsid();
3413
3414     for (i = 0; i < 3; i++) {
3415         close(i);
3416         open("/dev/null", O_RDWR);
3417     }
3418     return 1;
3419 }
3420 #endif
3421
3422 void *sighandler(void *arg) {
3423     sigset_t sigset;
3424     int sig;
3425
3426     for(;;) {
3427         sigemptyset(&sigset);
3428         sigaddset(&sigset, SIGPIPE);
3429         sigwait(&sigset, &sig);
3430         /* only get SIGPIPE right now, so could simplify below code */
3431         switch (sig) {
3432         case 0:
3433             /* completely ignoring this */
3434             break;
3435         case SIGPIPE:
3436             debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3437             break;
3438         default:
3439             debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3440         }
3441     }
3442 }
3443
3444 int main(int argc, char **argv) {
3445     pthread_t sigth;
3446     sigset_t sigset;
3447     struct list_node *entry;
3448     uint8_t foreground = 0, pretend = 0, loglevel = 0;
3449     char *configfile = NULL;
3450     struct clsrvconf *srvconf;
3451     int i;
3452     
3453     debug_init("radsecproxy");
3454     debug_set_level(DEBUG_LEVEL);
3455     pthread_mutex_init(&tlsconfs_lock, NULL);
3456     
3457     getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3458     if (loglevel)
3459         debug_set_level(loglevel);
3460     getmainconfig(configfile ? configfile : CONFIG_MAIN);
3461     if (loglevel)
3462         options.loglevel = loglevel;
3463     else if (options.loglevel)
3464         debug_set_level(options.loglevel);
3465     if (!foreground)
3466         debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3467     free(options.logdestination);
3468
3469     if (!list_first(clconfs))
3470         debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3471     if (!list_first(realms))
3472         debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3473
3474     if (pretend)
3475         debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3476
3477     if (!foreground && (daemon(0, 0) < 0))
3478         debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3479     
3480     debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3481
3482     sigemptyset(&sigset);
3483     /* exit on all but SIGPIPE, ignore more? */
3484     sigaddset(&sigset, SIGPIPE);
3485     pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3486     pthread_create(&sigth, NULL, sighandler, NULL);
3487
3488     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3489         srvconf = (struct clsrvconf *)entry->data;
3490         if (srvconf->dynamiclookupcommand)
3491             continue;
3492         if (!addserver(srvconf))
3493             debugx(1, DBG_ERR, "failed to add server");
3494         if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3495                            (void *)(srvconf->servers)))
3496             debugx(1, DBG_ERR, "pthread_create failed");
3497     }
3498     /* srcprotores for UDP no longer needed */
3499     if (srcprotores[RAD_UDP]) {
3500         freeaddrinfo(srcprotores[RAD_UDP]);
3501         srcprotores[RAD_UDP] = NULL;
3502     }
3503
3504     for (i = 0; protodefs[i].name; i++)
3505         if (protodefs[i].initextra)
3506             protodefs[i].initextra();
3507     
3508     if (find_clconf_type(RAD_TCP, NULL))
3509         createlisteners(RAD_TCP, options.listentcp);
3510     
3511     if (find_clconf_type(RAD_TLS, NULL))
3512         createlisteners(RAD_TLS, options.listentls);
3513     
3514     if (find_clconf_type(RAD_DTLS, NULL))
3515         createlisteners(RAD_DTLS, options.listendtls);
3516     
3517     if (find_clconf_type(RAD_UDP, NULL)) {
3518         createlisteners(RAD_UDP, options.listenudp);
3519         if (options.listenaccudp)
3520             createlisteners(RAD_UDP, options.listenaccudp);
3521     }
3522     
3523     /* just hang around doing nothing, anything to do here? */
3524     for (;;)
3525         sleep(1000);
3526 }