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