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