48543ef917210fc94d98189b25d97cc5542fb8a2
[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 *resizeattr(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, "resizeattr: 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     if (reslen > 253) {
1613         debug(DBG_WARN, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1614         free(in);
1615         return 0;
1616     }
1617     result = resizeattr(buf, attr, reslen);
1618     if (!result) {
1619         free(in);
1620         return 0;
1621     }
1622     
1623     start = 0;
1624     reslen = 0;
1625     for (i = start; out[i]; i++) {
1626         if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1627             pfield = &pmatch[out[i + 1] - '0'];
1628             if (pfield->rm_so >= 0) {
1629                 memcpy(result + reslen, out + start, i - start);
1630                 reslen += i - start;
1631                 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1632                 reslen += pfield->rm_eo - pfield->rm_so;
1633                 start = i + 2;
1634             }
1635             i++;
1636         }
1637     }
1638
1639     memcpy(result + reslen, out + start, i - start);
1640     return 1;
1641 }
1642    
1643 int dorewritemod(uint8_t **buf, struct list *modattrs) {
1644     uint8_t *attr;
1645     uint16_t len = 0;
1646     struct list_node *n;
1647
1648     attr = *buf + 20;
1649     while (RADLEN(*buf) - 22 >= len) {
1650         for (n = list_first(modattrs); n; n = list_next(n))
1651             if (ATTRTYPE(attr) == ((struct modattr *)n->data)->t)
1652                 if (!dorewritemodattr(buf, &attr, (struct modattr *)n->data))
1653                     return 0;
1654         len += ATTRLEN(attr);
1655         attr += ATTRLEN(attr);
1656     }
1657     return 1;
1658 }
1659
1660 int dorewrite(uint8_t **buf, struct rewrite *rewrite) {
1661     if (!rewrite)
1662         return 1;
1663     if (rewrite->removeattrs || rewrite->removevendorattrs)
1664         dorewriterm(*buf, rewrite->removeattrs, rewrite->removevendorattrs);
1665     if (rewrite->addattrs && !dorewriteadd(buf, rewrite->addattrs))
1666         return 0;
1667     if (rewrite->modattrs && !dorewritemod(buf, rewrite->modattrs))
1668         return 0;
1669     return 1;
1670 }
1671     
1672 int rewriteusername(struct request *rq, uint8_t *attr, char *in) {
1673     if (!dorewritemodattr(&rq->buf, &attr, rq->from->conf->rewriteusername))
1674         return 0;
1675     if (strlen(in) == ATTRVALLEN(attr) && !memcmp(in, ATTRVAL(attr), ATTRVALLEN(attr)))
1676         return 1;
1677
1678     rq->origusername = stringcopy(in, 0);
1679     if (!rq->origusername)
1680         return 0;
1681     
1682     memcpy(in, ATTRVAL(attr), ATTRVALLEN(attr));
1683     in[ATTRVALLEN(attr)] = '\0';
1684     return 1;
1685 }
1686
1687 const char *radmsgtype2string(uint8_t code) {
1688     static const char *rad_msg_names[] = {
1689         "", "Access-Request", "Access-Accept", "Access-Reject",
1690         "Accounting-Request", "Accounting-Response", "", "",
1691         "", "", "", "Access-Challenge",
1692         "Status-Server", "Status-Client"
1693     };
1694     return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1695 }
1696
1697 void char2hex(char *h, unsigned char c) {
1698     static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1699                                       '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1700     h[0] = hexdigits[c / 16];
1701     h[1] = hexdigits[c % 16];
1702     return;
1703 }
1704
1705 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
1706     int i, l;
1707     char *s, *d;
1708
1709     if (!attr || len == 1) {
1710         *ascii = '\0';
1711         return ascii;
1712     }
1713
1714     l = ATTRVALLEN(attr);
1715     s = (char *)ATTRVAL(attr);
1716     d = ascii;
1717
1718     for (i = 0; i < l; i++) {
1719         if (s[i] > 31 && s[i] < 127) {
1720             *d++ = s[i];
1721             if (d - ascii == len - 1)
1722                 break;
1723         } else {
1724             if (d - ascii > len - 4)
1725                 break;
1726             *d++ = '%';
1727             char2hex(d, s[i]);
1728             d += 2;
1729             if (d - ascii == len - 1)
1730                 break;
1731         }
1732     }
1733     *d = '\0';
1734     return ascii;
1735 }
1736
1737 void acclog(unsigned char *attrs, int length, char *host) {
1738     unsigned char *attr;
1739     char username[760];
1740     
1741     attr = attrget(attrs, length, RAD_Attr_User_Name);
1742     if (!attr) {
1743         debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1744         return;
1745     }
1746     radattr2ascii(username, sizeof(username), attr);
1747     debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1748 }
1749         
1750 void respondaccounting(struct request *rq) {
1751     unsigned char *resp;
1752
1753     resp = malloc(20);
1754     if (!resp) {
1755         debug(DBG_ERR, "respondaccounting: malloc failed");
1756         return;
1757     }
1758     memcpy(resp, rq->buf, 20);
1759     resp[0] = RAD_Accounting_Response;
1760     resp[2] = 0;
1761     resp[3] = 20;
1762     debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1763     sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1764 }
1765
1766 void respondstatusserver(struct request *rq) {
1767     unsigned char *resp;
1768
1769     resp = malloc(20);
1770     if (!resp) {
1771         debug(DBG_ERR, "respondstatusserver: malloc failed");
1772         return;
1773     }
1774     memcpy(resp, rq->buf, 20);
1775     resp[0] = RAD_Access_Accept;
1776     resp[2] = 0;
1777     resp[3] = 20;
1778     debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1779     sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1780 }
1781
1782 void respondreject(struct request *rq, char *message) {
1783     unsigned char *resp;
1784     int len = 20;
1785
1786     if (message && *message)
1787         len += 2 + strlen(message);
1788     
1789     resp = malloc(len);
1790     if (!resp) {
1791         debug(DBG_ERR, "respondreject: malloc failed");
1792         return;
1793     }
1794     memcpy(resp, rq->buf, 20);
1795     resp[0] = RAD_Access_Reject;
1796     *(uint16_t *)(resp + 2) = htons(len);
1797     if (message && *message) {
1798         resp[20] = RAD_Attr_Reply_Message;
1799         resp[21] = len - 20;
1800         memcpy(resp + 22, message, len - 22);
1801     }
1802     sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1803 }
1804
1805 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1806     struct list_node *entry;
1807     struct clsrvconf *server, *best = NULL, *first = NULL;
1808
1809     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1810         server = (struct clsrvconf *)entry->data;
1811         if (!server->servers)
1812             return server;
1813         if (!first)
1814             first = server;
1815         if (!server->servers->connectionok)
1816             continue;
1817         if (!server->servers->lostrqs)
1818             return server;
1819         if (!best) {
1820             best = server;
1821             continue;
1822         }
1823         if (server->servers->lostrqs < best->servers->lostrqs)
1824             best = server;
1825     }
1826     return best ? best : first;
1827 }
1828
1829 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
1830     struct clsrvconf *srvconf;
1831     
1832     *realm = id2realm(realms, id);
1833     if (!*realm)
1834         return NULL;
1835     debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1836     srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1837     if (!srvconf)
1838         return NULL;
1839     if (!acc && !srvconf->servers)
1840         adddynamicrealmserver(*realm, srvconf, id);
1841     return srvconf->servers;
1842 }
1843
1844 /* returns 0 if validation/authentication fails, else 1 */
1845 int radsrv(struct request *rq) {
1846     uint8_t code, id, *auth, *attrs, *attr;
1847     uint16_t len;
1848     struct server *to = NULL;
1849     char username[254], userascii[760];
1850     unsigned char newauth[16];
1851     struct realm *realm = NULL;
1852     
1853     code = *(uint8_t *)rq->buf;
1854     id = *(uint8_t *)(rq->buf + 1);
1855     len = RADLEN(rq->buf);
1856     auth = (uint8_t *)(rq->buf + 4);
1857
1858     debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1859     
1860     if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1861         debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1862         goto exit;
1863     }
1864
1865     len -= 20;
1866     attrs = rq->buf + 20;
1867
1868     if (!attrvalidate(attrs, len)) {
1869         debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1870         goto errvalauth;
1871     }
1872
1873     attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1874     if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
1875         debug(DBG_WARN, "radsrv: message authentication failed");
1876         goto errvalauth;
1877     }
1878
1879     if (code == RAD_Status_Server) {
1880         respondstatusserver(rq);
1881         goto exit;
1882     }
1883     
1884     /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1885
1886     if (code == RAD_Accounting_Request) {
1887         memset(newauth, 0, 16);
1888         if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
1889             debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
1890             goto errvalauth;
1891         }
1892     }
1893     
1894     if (rq->from->conf->rewritein) {
1895         if (!dorewrite(&rq->buf, rq->from->conf->rewritein))
1896             goto exit;
1897         len = RADLEN(rq->buf) - 20;
1898         auth = (uint8_t *)(rq->buf + 4);
1899         attrs = rq->buf + 20;
1900     }
1901     
1902     attr = attrget(attrs, len, RAD_Attr_User_Name);
1903     if (!attr) {
1904         if (code == RAD_Accounting_Request) {
1905             acclog(attrs, len, rq->from->conf->host);
1906             respondaccounting(rq);
1907         } else
1908             debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1909         goto exit;
1910     }
1911     memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1912     username[ATTRVALLEN(attr)] = '\0';
1913     radattr2ascii(userascii, sizeof(userascii), attr);
1914
1915     if (rq->from->conf->rewriteusername) {
1916         if (!rewriteusername(rq, attr, username)) {
1917             debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1918             goto exit;
1919         }
1920         len = RADLEN(rq->buf) - 20;
1921         auth = (uint8_t *)(rq->buf + 4);
1922         attrs = rq->buf + 20;
1923     }
1924
1925     debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
1926     
1927     to = findserver(&realm, username, code == RAD_Accounting_Request);
1928     if (!realm) {
1929         debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1930         goto exit;
1931     }
1932     if (!to) {
1933         if (realm->message && code == RAD_Access_Request) {
1934             debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
1935             respondreject(rq, realm->message);
1936         } else if (realm->accresp && code == RAD_Accounting_Request) {
1937             acclog(attrs, len, rq->from->conf->host);
1938             respondaccounting(rq);
1939         }
1940         goto exit;
1941     }
1942     
1943     if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
1944         debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
1945               rq->from->conf->name, to->conf->name);
1946         goto exit;
1947     }
1948
1949     if (rqinqueue(to, rq->from, id, code)) {
1950         debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
1951               radmsgtype2string(code), rq->from->conf->host, id);
1952         goto exit;
1953     }
1954     
1955     if (code != RAD_Accounting_Request) {
1956         if (!RAND_bytes(newauth, 16)) {
1957             debug(DBG_WARN, "radsrv: failed to generate random auth");
1958             goto exit;
1959         }
1960     }
1961
1962 #ifdef DEBUG
1963     printfchars(NULL, "auth", "%02x ", auth, 16);
1964 #endif
1965
1966     attr = attrget(attrs, len, RAD_Attr_User_Password);
1967     if (attr) {
1968         debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1969         if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
1970             goto exit;
1971     }
1972     
1973     attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1974     if (attr) {
1975         debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1976         if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
1977             goto exit;
1978     }
1979
1980     rq->origid = id;
1981     memcpy(rq->origauth, auth, 16);
1982     memcpy(auth, newauth, 16);
1983
1984     if (to->conf->rewriteout)
1985         if (!dorewrite(&rq->buf, to->conf->rewriteout))
1986             goto exit;
1987     
1988     sendrq(to, rq);
1989     return 1;
1990     
1991  exit:
1992     freerqdata(rq);
1993     return 1;
1994
1995  errvalauth:
1996     freerqdata(rq);
1997     return 0;
1998 }
1999
2000 int replyh(struct server *server, unsigned char *buf) {
2001     struct client *from;
2002     struct request *rq;
2003     int i, len, sublen;
2004     unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
2005     struct sockaddr_storage fromsa;
2006     char tmp[760], stationid[760];
2007     
2008     server->connectionok = 1;
2009     server->lostrqs = 0;
2010         
2011     i = buf[1]; /* i is the id */
2012
2013     if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
2014         && *buf != RAD_Accounting_Response) {
2015         debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
2016         return 0;
2017     }
2018     debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
2019
2020     rq = server->requests + i;
2021
2022     pthread_mutex_lock(&server->newrq_mutex);
2023     if (!rq->buf || !rq->tries) {
2024         pthread_mutex_unlock(&server->newrq_mutex);
2025         debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
2026         return 0;
2027     }
2028
2029     if (rq->received) {
2030         pthread_mutex_unlock(&server->newrq_mutex);
2031         debug(DBG_INFO, "replyh: already received, ignoring reply");
2032         return 0;
2033     }
2034         
2035     if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
2036         pthread_mutex_unlock(&server->newrq_mutex);
2037         debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
2038         return 0;
2039     }
2040         
2041     len = RADLEN(buf) - 20;
2042     attrs = buf + 20;
2043
2044     if (!attrvalidate(attrs, len)) {
2045         pthread_mutex_unlock(&server->newrq_mutex);
2046         debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
2047         return 0;
2048     }
2049         
2050     /* Message Authenticator */
2051     messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2052     if (messageauth) {
2053         if (ATTRVALLEN(messageauth) != 16) {
2054             pthread_mutex_unlock(&server->newrq_mutex);
2055             debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
2056             return 0;
2057         }
2058         memcpy(tmp, buf + 4, 16);
2059         memcpy(buf + 4, rq->buf + 4, 16);
2060         if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
2061             pthread_mutex_unlock(&server->newrq_mutex);
2062             debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
2063             return 0;
2064         }
2065         memcpy(buf + 4, tmp, 16);
2066         debug(DBG_DBG, "replyh: message auth ok");
2067     }
2068     
2069     gettimeofday(&server->lastrcv, NULL);
2070     
2071     if (*rq->buf == RAD_Status_Server) {
2072         rq->received = 1;
2073         pthread_mutex_unlock(&server->newrq_mutex);
2074         debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2075         return 0;
2076     }
2077
2078     gettimeofday(&server->lastreply, NULL);
2079     
2080     from = rq->from;
2081     if (!from) {
2082         pthread_mutex_unlock(&server->newrq_mutex);
2083         debug(DBG_INFO, "replyh: client gone, ignoring reply");
2084         return 0;
2085     }
2086         
2087     if (server->conf->rewritein) {
2088         if (!dorewrite(&buf, server->conf->rewritein))
2089             return 0;
2090         len = RADLEN(buf) - 20;
2091         attrs = buf + 20;
2092         if (messageauth)
2093             messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2094     }
2095     
2096     /* MS MPPE */
2097     for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2098         if (ATTRVALLEN(attr) <= 4)
2099             break;
2100             
2101         if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55)  /* 311 == MS */
2102             continue;
2103             
2104         sublen = ATTRVALLEN(attr) - 4;
2105         subattrs = ATTRVAL(attr) + 4;  
2106         if (!attrvalidate(subattrs, sublen) ||
2107             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2108                     rq, server->conf->secret, from->conf->secret) ||
2109             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2110                     rq, server->conf->secret, from->conf->secret))
2111             break;
2112     }
2113     if (attr) {
2114         pthread_mutex_unlock(&server->newrq_mutex);
2115         debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2116         return 0;
2117     }
2118         
2119     if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2120         attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2121         if (attr) {
2122             radattr2ascii(tmp, sizeof(tmp), attr);
2123             attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2124             if (attr) {
2125                 radattr2ascii(stationid, sizeof(stationid), attr);
2126                 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2127                       radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2128             } else
2129                 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2130         }
2131     }
2132         
2133     buf[1] = (char)rq->origid;
2134     memcpy(buf + 4, rq->origauth, 16);
2135 #ifdef DEBUG    
2136     printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2137 #endif
2138
2139     if (rq->origusername && (attr = attrget(buf + 20, RADLEN(buf) - 20, RAD_Attr_User_Name))) {
2140         username = resizeattr(&buf, &attr, strlen(rq->origusername));
2141         if (!username) {
2142             pthread_mutex_unlock(&server->newrq_mutex);
2143             debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2144             return 0;
2145         }
2146         memcpy(username, rq->origusername, strlen(rq->origusername));
2147         len = RADLEN(buf) - 20;
2148         attrs = buf + 20;
2149         if (messageauth)
2150             messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2151     }
2152     
2153     if (from->conf->rewriteout) {
2154         if (!dorewrite(&buf, from->conf->rewriteout))
2155             return 0;
2156         len = RADLEN(buf) - 20;
2157         attrs = buf + 20;
2158         if (messageauth)
2159             messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2160     }
2161         
2162     if (messageauth) {
2163         if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2164             pthread_mutex_unlock(&server->newrq_mutex);
2165             debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2166             return 0;
2167         }
2168         debug(DBG_DBG, "replyh: computed messageauthattr");
2169     }
2170
2171     fromsa = rq->fromsa; /* only needed for UDP */
2172     /* once we set received = 1, rq may be reused */
2173     rq->received = 1;
2174
2175     debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2176     sendreply(from, buf, &fromsa, rq->fromudpsock);
2177     pthread_mutex_unlock(&server->newrq_mutex);
2178     return 1;
2179 }
2180
2181 /* code for removing state not finished */
2182 void *clientwr(void *arg) {
2183     struct server *server = (struct server *)arg;
2184     struct request *rq;
2185     pthread_t clientrdth;
2186     int i, secs, dynconffail = 0;
2187     uint8_t rnd;
2188     struct timeval now, laststatsrv;
2189     struct timespec timeout;
2190     struct request statsrvrq;
2191     unsigned char statsrvbuf[38];
2192     struct clsrvconf *conf;
2193     
2194     conf = server->conf;
2195     
2196     if (server->dynamiclookuparg && !dynamicconfig(server)) {
2197         dynconffail = 1;
2198         goto errexit;
2199     }
2200     
2201     if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2202         debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2203         goto errexit;
2204     }
2205
2206     memset(&timeout, 0, sizeof(struct timespec));
2207     
2208     if (conf->statusserver) {
2209         memset(&statsrvrq, 0, sizeof(struct request));
2210         memset(statsrvbuf, 0, sizeof(statsrvbuf));
2211         statsrvbuf[0] = RAD_Status_Server;
2212         statsrvbuf[3] = 38;
2213         statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2214         statsrvbuf[21] = 18;
2215         gettimeofday(&server->lastrcv, NULL);
2216         gettimeofday(&laststatsrv, NULL);
2217     }
2218
2219     if (conf->pdef->connecter) {
2220         if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2221             goto errexit;
2222         server->connectionok = 1;
2223         if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
2224             debug(DBG_ERR, "clientwr: pthread_create failed");
2225             goto errexit;
2226         }
2227     } else
2228         server->connectionok = 1;
2229     
2230     for (;;) {
2231         pthread_mutex_lock(&server->newrq_mutex);
2232         if (!server->newrq) {
2233             gettimeofday(&now, NULL);
2234             /* random 0-7 seconds */
2235             RAND_bytes(&rnd, 1);
2236             rnd /= 32;
2237             if (conf->statusserver) {
2238                 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2239                 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
2240                     timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
2241             } else {
2242                 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2243                     timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2244             }
2245 #if 0
2246             if (timeout.tv_sec > now.tv_sec)
2247                 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2248 #endif      
2249             pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2250             timeout.tv_sec = 0;
2251         }
2252         if (server->newrq) {
2253             debug(DBG_DBG, "clientwr: got new request");
2254             server->newrq = 0;
2255         }
2256 #if 0   
2257         else
2258             debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2259 #endif  
2260         pthread_mutex_unlock(&server->newrq_mutex);
2261
2262         for (i = 0; i < MAX_REQUESTS; i++) {
2263             if (server->clientrdgone) {
2264                 pthread_join(clientrdth, NULL);
2265                 goto errexit;
2266             }
2267             pthread_mutex_lock(&server->newrq_mutex);
2268             while (i < MAX_REQUESTS && !server->requests[i].buf)
2269                 i++;
2270             if (i == MAX_REQUESTS) {
2271                 pthread_mutex_unlock(&server->newrq_mutex);
2272                 break;
2273             }
2274             rq = server->requests + i;
2275
2276             if (rq->received) {
2277                 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2278                 if (rq->buf) {
2279                     debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2280                     freerqdata(rq);
2281                     /* setting this to NULL means that it can be reused */
2282                     rq->buf = NULL;
2283                 }
2284                 pthread_mutex_unlock(&server->newrq_mutex);
2285                 continue;
2286             }
2287             
2288             gettimeofday(&now, NULL);
2289             if (now.tv_sec < rq->expiry.tv_sec) {
2290                 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2291                     timeout.tv_sec = rq->expiry.tv_sec;
2292                 pthread_mutex_unlock(&server->newrq_mutex);
2293                 continue;
2294             }
2295
2296             if (rq->tries == (*rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2297                 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2298                 if (conf->statusserver) {
2299                     if (*rq->buf == RAD_Status_Server) {
2300                         debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2301                         if (server->lostrqs < 255)
2302                             server->lostrqs++;
2303                     }
2304                 } else {
2305                     debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2306                     if (server->lostrqs < 255)
2307                         server->lostrqs++;
2308                 }
2309                 freerqdata(rq);
2310                 /* setting this to NULL means that it can be reused */
2311                 rq->buf = NULL;
2312                 pthread_mutex_unlock(&server->newrq_mutex);
2313                 continue;
2314             }
2315             pthread_mutex_unlock(&server->newrq_mutex);
2316
2317             rq->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2318             if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2319                 timeout.tv_sec = rq->expiry.tv_sec;
2320             rq->tries++;
2321             conf->pdef->clientradput(server, server->requests[i].buf);
2322         }
2323         if (conf->statusserver) {
2324             secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2325             gettimeofday(&now, NULL);
2326             if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
2327                 laststatsrv = now;
2328                 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2329                     debug(DBG_WARN, "clientwr: failed to generate random auth");
2330                     continue;
2331                 }
2332                 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2333                 if (!statsrvrq.buf) {
2334                     debug(DBG_ERR, "clientwr: malloc failed");
2335                     continue;
2336                 }
2337                 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2338                 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2339                 sendrq(server, &statsrvrq);
2340             }
2341         }
2342     }
2343  errexit:
2344     conf->servers = NULL;
2345     if (server->dynamiclookuparg) {
2346         removeserversubrealms(realms, conf);
2347         if (dynconffail)
2348             free(conf);
2349         else
2350             freeclsrvconf(conf);
2351     }
2352     freeserver(server, 1);
2353     ERR_remove_state(0);
2354     return NULL;
2355 }
2356
2357 void createlistener(uint8_t type, char *arg) {
2358     pthread_t th;
2359     struct clsrvconf *listenres;
2360     struct addrinfo *res;
2361     int s = -1, on = 1, *sp = NULL;
2362     
2363     listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2364     if (!listenres)
2365         debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2366     
2367     for (res = listenres->addrinfo; res; res = res->ai_next) {
2368         s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2369         if (s < 0) {
2370             debug(DBG_WARN, "createlistener: socket failed");
2371             continue;
2372         }
2373         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2374 #ifdef IPV6_V6ONLY
2375         if (res->ai_family == AF_INET6)
2376             setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2377 #endif          
2378         if (bind(s, res->ai_addr, res->ai_addrlen)) {
2379             debug(DBG_WARN, "createlistener: bind failed");
2380             close(s);
2381             s = -1;
2382             continue;
2383         }
2384
2385         sp = malloc(sizeof(int));
2386         if (!sp)
2387             debugx(1, DBG_ERR, "malloc failed");
2388         *sp = s;
2389         if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
2390             debugx(1, DBG_ERR, "pthread_create failed");
2391         pthread_detach(th);
2392     }
2393     if (!sp)
2394         debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2395     
2396     debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
2397           listenres->host ? listenres->host : "*", listenres->port);
2398     freeclsrvres(listenres);
2399 }
2400
2401 void createlisteners(uint8_t type, char **args) {
2402     int i;
2403
2404     if (args)
2405         for (i = 0; args[i]; i++)
2406             createlistener(type, args[i]);
2407     else
2408         createlistener(type, NULL);
2409 }
2410
2411 #ifdef DEBUG
2412 void ssl_info_callback(const SSL *ssl, int where, int ret) {
2413     const char *s;
2414     int w;
2415
2416     w = where & ~SSL_ST_MASK;
2417
2418     if (w & SSL_ST_CONNECT)
2419         s = "SSL_connect";
2420     else if (w & SSL_ST_ACCEPT)
2421         s = "SSL_accept";
2422     else
2423         s = "undefined";
2424
2425     if (where & SSL_CB_LOOP)
2426         debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
2427     else if (where & SSL_CB_ALERT) {
2428         s = (where & SSL_CB_READ) ? "read" : "write";
2429         debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
2430     }
2431     else if (where & SSL_CB_EXIT) {
2432         if (ret == 0)
2433             debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
2434         else if (ret < 0)
2435             debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
2436     }
2437 }
2438 #endif
2439
2440 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2441     SSL_CTX *ctx = NULL;
2442     STACK_OF(X509_NAME) *calist;
2443     X509_STORE *x509_s;
2444     int i;
2445     unsigned long error;
2446
2447     if (!ssl_locks) {
2448         ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2449         ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2450         for (i = 0; i < CRYPTO_num_locks(); i++) {
2451             ssl_lock_count[i] = 0;
2452             pthread_mutex_init(&ssl_locks[i], NULL);
2453         }
2454         CRYPTO_set_id_callback(ssl_thread_id);
2455         CRYPTO_set_locking_callback(ssl_locking_callback);
2456
2457         SSL_load_error_strings();
2458         SSL_library_init();
2459
2460         while (!RAND_status()) {
2461             time_t t = time(NULL);
2462             pid_t pid = getpid();
2463             RAND_seed((unsigned char *)&t, sizeof(time_t));
2464             RAND_seed((unsigned char *)&pid, sizeof(pid));
2465         }
2466     }
2467
2468     switch (type) {
2469     case RAD_TLS:
2470         ctx = SSL_CTX_new(TLSv1_method());
2471 #ifdef DEBUG    
2472         SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2473 #endif  
2474         break;
2475     case RAD_DTLS:
2476         ctx = SSL_CTX_new(DTLSv1_method());
2477 #ifdef DEBUG    
2478         SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2479 #endif  
2480         SSL_CTX_set_read_ahead(ctx, 1);
2481         break;
2482     }
2483     if (!ctx) {
2484         debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2485         return NULL;
2486     }
2487     
2488     if (conf->certkeypwd) {
2489         SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2490         SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2491     }
2492     if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2493         !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2494         !SSL_CTX_check_private_key(ctx) ||
2495         !SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2496         while ((error = ERR_get_error()))
2497             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2498         debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2499         SSL_CTX_free(ctx);
2500         return NULL;
2501     }
2502
2503     calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2504     if (!conf->cacertfile || calist) {
2505         if (conf->cacertpath) {
2506             if (!calist)
2507                 calist = sk_X509_NAME_new_null();
2508             if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2509                 sk_X509_NAME_free(calist);
2510                 calist = NULL;
2511             }
2512         }
2513     }
2514     if (!calist) {
2515         while ((error = ERR_get_error()))
2516             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2517         debug(DBG_ERR, "tlscreatectx: Error adding CA subjects in TLS context %s", conf->name);
2518         SSL_CTX_free(ctx);
2519         return NULL;
2520     }
2521     ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2522     SSL_CTX_set_client_CA_list(ctx, calist);
2523     
2524     SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2525     SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2526
2527     if (conf->crlcheck) {
2528         x509_s = SSL_CTX_get_cert_store(ctx);
2529         X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2530     }
2531
2532     debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
2533     return ctx;
2534 }
2535
2536 SSL_CTX *tlsgetctx(uint8_t type, char *alt1, char *alt2) {
2537     struct tls *t;
2538
2539     t = hash_read(tlsconfs, alt1, strlen(alt1));
2540     if (!t) {
2541         t = hash_read(tlsconfs, alt2, strlen(alt2));
2542         if (!t)
2543             return NULL;
2544     }
2545
2546     switch (type) {
2547     case RAD_TLS:
2548         if (!t->tlsctx)
2549             t->tlsctx = tlscreatectx(RAD_TLS, t);
2550         return t->tlsctx;
2551     case RAD_DTLS:
2552         if (!t->dtlsctx)
2553             t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2554         return t->dtlsctx;
2555     }
2556     return NULL;
2557 }
2558
2559 struct list *addsrvconfs(char *value, char **names) {
2560     struct list *conflist;
2561     int n;
2562     struct list_node *entry;
2563     struct clsrvconf *conf = NULL;
2564     
2565     if (!names || !*names)
2566         return NULL;
2567     
2568     conflist = list_create();
2569     if (!conflist) {
2570         debug(DBG_ERR, "malloc failed");
2571         return NULL;
2572     }
2573
2574     for (n = 0; names[n]; n++) {
2575         for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2576             conf = (struct clsrvconf *)entry->data;
2577             if (!strcasecmp(names[n], conf->name))
2578                 break;
2579         }
2580         if (!entry) {
2581             debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2582             list_destroy(conflist);
2583             return NULL;
2584         }
2585         if (!list_push(conflist, conf)) {
2586             debug(DBG_ERR, "malloc failed");
2587             list_destroy(conflist);
2588             return NULL;
2589         }
2590         debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2591     }
2592     return conflist;
2593 }
2594
2595 void freerealm(struct realm *realm) {
2596     if (!realm)
2597         return;
2598     free(realm->name);
2599     free(realm->message);
2600     regfree(&realm->regex);
2601     pthread_mutex_destroy(&realm->subrealms_mutex);
2602     if (realm->subrealms)
2603         list_destroy(realm->subrealms);
2604     if (realm->srvconfs) {
2605         /* emptying list without freeing data */
2606         while (list_shift(realm->srvconfs));
2607         list_destroy(realm->srvconfs);
2608     }
2609     if (realm->accsrvconfs) {
2610         /* emptying list without freeing data */
2611         while (list_shift(realm->accsrvconfs));
2612         list_destroy(realm->accsrvconfs);
2613     }
2614     free(realm);
2615 }
2616
2617 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2618     int n;
2619     struct realm *realm;
2620     char *s, *regex = NULL;
2621     
2622     if (*value == '/') {
2623         /* regexp, remove optional trailing / if present */
2624         if (value[strlen(value) - 1] == '/')
2625             value[strlen(value) - 1] = '\0';
2626     } else {
2627         /* not a regexp, let us make it one */
2628         if (*value == '*' && !value[1])
2629             regex = stringcopy(".*", 0);
2630         else {
2631             for (n = 0, s = value; *s;)
2632                 if (*s++ == '.')
2633                     n++;
2634             regex = malloc(strlen(value) + n + 3);
2635             if (regex) {
2636                 regex[0] = '@';
2637                 for (n = 1, s = value; *s; s++) {
2638                     if (*s == '.')
2639                         regex[n++] = '\\';
2640                     regex[n++] = *s;
2641                 }
2642                 regex[n++] = '$';
2643                 regex[n] = '\0';
2644             }
2645         }
2646         if (!regex) {
2647             debug(DBG_ERR, "malloc failed");
2648             realm = NULL;
2649             goto exit;
2650         }
2651         debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2652     }
2653
2654     realm = malloc(sizeof(struct realm));
2655     if (!realm) {
2656         debug(DBG_ERR, "malloc failed");
2657         goto exit;
2658     }
2659     memset(realm, 0, sizeof(struct realm));
2660     
2661     if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
2662         debug(DBG_ERR, "mutex init failed");
2663         free(realm);
2664         realm = NULL;
2665         goto exit;
2666     }
2667
2668     realm->name = stringcopy(value, 0);
2669     if (!realm->name) {
2670         debug(DBG_ERR, "malloc failed");
2671         goto errexit;
2672     }
2673     if (message && strlen(message) > 253) {
2674         debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2675         goto errexit;
2676     }
2677     realm->message = message;
2678     realm->accresp = accresp;
2679     
2680     if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2681         debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2682         goto errexit;
2683     }
2684     
2685     if (servers && *servers) {
2686         realm->srvconfs = addsrvconfs(value, servers);
2687         if (!realm->srvconfs)
2688             goto errexit;
2689     }
2690     
2691     if (accservers && *accservers) {
2692         realm->accsrvconfs = addsrvconfs(value, accservers);
2693         if (!realm->accsrvconfs)
2694             goto errexit;
2695     }
2696
2697     if (!list_push(realmlist, realm)) {
2698         debug(DBG_ERR, "malloc failed");
2699         pthread_mutex_destroy(&realm->subrealms_mutex);
2700         goto errexit;
2701     }
2702     
2703     debug(DBG_DBG, "addrealm: added realm %s", value);
2704     goto exit;
2705
2706  errexit:
2707     freerealm(realm);
2708     realm = NULL;
2709     
2710  exit:
2711     free(regex);
2712     if (servers) {
2713         for (n = 0; servers[n]; n++)
2714             free(servers[n]);
2715         free(servers);
2716     }
2717     if (accservers) {
2718         for (n = 0; accservers[n]; n++)
2719             free(accservers[n]);
2720         free(accservers);
2721     }
2722     return realm;
2723 }
2724
2725 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2726     struct clsrvconf *srvconf;
2727     struct realm *newrealm = NULL;
2728     char *realmname, *s;
2729     pthread_t clientth;
2730     
2731     if (!conf->dynamiclookupcommand)
2732         return;
2733
2734     /* create dynamic for the realm (string after last @, exit if nothing after @ */
2735     realmname = strrchr(id, '@');
2736     if (!realmname)
2737         return;
2738     realmname++;
2739     if (!*realmname)
2740         return;
2741     for (s = realmname; *s; s++)
2742         if (*s != '.' && *s != '-' && !isalnum((int)*s))
2743             return;
2744     
2745     pthread_mutex_lock(&realm->subrealms_mutex);
2746     /* exit if we now already got a matching subrealm */
2747     if (id2realm(realm->subrealms, id))
2748         goto exit;
2749     srvconf = malloc(sizeof(struct clsrvconf));
2750     if (!srvconf) {
2751         debug(DBG_ERR, "malloc failed");
2752         goto exit;
2753     }
2754     *srvconf = *conf;
2755     if (!addserver(srvconf))
2756         goto errexit;
2757
2758     if (!realm->subrealms)
2759         realm->subrealms = list_create();
2760     if (!realm->subrealms)
2761         goto errexit;
2762     newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2763     if (!newrealm)
2764         goto errexit;
2765
2766     /* add server and accserver to newrealm */
2767     newrealm->srvconfs = list_create();
2768     if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2769         debug(DBG_ERR, "malloc failed");
2770         goto errexit;
2771     }
2772     newrealm->accsrvconfs = list_create();
2773     if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2774         debug(DBG_ERR, "malloc failed");
2775         goto errexit;
2776     }
2777
2778     srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2779
2780     if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2781         debug(DBG_ERR, "pthread_create failed");
2782         goto errexit;
2783     }
2784     pthread_detach(clientth);
2785     goto exit;
2786     
2787  errexit:
2788     if (newrealm) {
2789         list_removedata(realm->subrealms, newrealm);
2790         freerealm(newrealm);
2791         if (!list_first(realm->subrealms)) {
2792             list_destroy(realm->subrealms);
2793             realm->subrealms = NULL;
2794         }
2795     }
2796     freeserver(srvconf->servers, 1);
2797     free(srvconf);
2798     debug(DBG_ERR, "failed to create dynamic server");
2799
2800  exit:
2801     pthread_mutex_unlock(&realm->subrealms_mutex);
2802 }
2803
2804 int dynamicconfig(struct server *server) {
2805     int ok, fd[2], status;
2806     pid_t pid;
2807     struct clsrvconf *conf = server->conf;
2808     struct gconffile *cf = NULL;
2809     
2810     /* for now we only learn hostname/address */
2811     debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2812
2813     if (pipe(fd) > 0) {
2814         debug(DBG_ERR, "dynamicconfig: pipe error");
2815         goto errexit;
2816     }
2817     pid = fork();
2818     if (pid < 0) {
2819         debug(DBG_ERR, "dynamicconfig: fork error");
2820         close(fd[0]);
2821         close(fd[1]);
2822         goto errexit;
2823     } else if (pid == 0) {
2824         /* child */
2825         close(fd[0]);
2826         if (fd[1] != STDOUT_FILENO) {
2827             if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2828                 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2829             close(fd[1]);
2830         }
2831         if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2832             debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2833     }
2834
2835     close(fd[1]);
2836     pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2837     ok = getgenericconfig(&cf, NULL,
2838                           "Server", CONF_CBK, confserver_cb, (void *)conf,
2839                           NULL
2840                           );
2841     freegconf(&cf);
2842         
2843     if (waitpid(pid, &status, 0) < 0) {
2844         debug(DBG_ERR, "dynamicconfig: wait error");
2845         goto errexit;
2846     }
2847     
2848     if (status) {
2849         debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2850         goto errexit;
2851     }
2852
2853     if (ok)
2854         return 1;
2855
2856  errexit:    
2857     debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2858     return 0;
2859 }
2860
2861 int addmatchcertattr(struct clsrvconf *conf) {
2862     char *v;
2863     regex_t **r;
2864     
2865     if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2866         r = &conf->certcnregex;
2867         v = conf->matchcertattr + 4;
2868     } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2869         r = &conf->certuriregex;
2870         v = conf->matchcertattr + 20;
2871     } else
2872         return 0;
2873     if (!*v)
2874         return 0;
2875     /* regexp, remove optional trailing / if present */
2876     if (v[strlen(v) - 1] == '/')
2877         v[strlen(v) - 1] = '\0';
2878     if (!*v)
2879         return 0;
2880
2881     *r = malloc(sizeof(regex_t));
2882     if (!*r) {
2883         debug(DBG_ERR, "malloc failed");
2884         return 0;
2885     }
2886     if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2887         free(*r);
2888         *r = NULL;
2889         debug(DBG_ERR, "failed to compile regular expression %s", v);
2890         return 0;
2891     }
2892     return 1;
2893 }
2894
2895 /* should accept both names and numeric values, only numeric right now */
2896 uint8_t attrname2val(char *attrname) {
2897     int val = 0;
2898     
2899     val = atoi(attrname);
2900     return val > 0 && val < 256 ? val : 0;
2901 }
2902
2903 /* should accept both names and numeric values, only numeric right now */
2904 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2905     char *s;
2906     
2907     *vendor = atoi(attrname);
2908     s = strchr(attrname, ':');
2909     if (!s) {
2910         *type = -1;
2911         return 1;
2912     }
2913     *type = atoi(s + 1);
2914     return *type >= 0 && *type < 256;
2915 }
2916
2917 /* should accept both names and numeric values, only numeric right now */
2918 struct attribute *extractattr(char *nameval) {
2919     int len, name = 0;
2920     char *s;
2921     struct attribute *a;
2922     
2923     s = strchr(nameval, ':');
2924     name = atoi(nameval);
2925     if (!s || name < 1 || name > 255)
2926         return NULL;
2927     len = strlen(s + 1);
2928     if (len > 253)
2929         return NULL;
2930     a = malloc(sizeof(struct attribute));
2931     if (!a)
2932         return NULL;
2933     a->v = (uint8_t *)stringcopy(s + 1, 0);
2934     if (!a->v) {
2935         free(a);
2936         return NULL;
2937     }
2938     a->t = name;
2939     a->l = len;
2940     return a;
2941 }
2942
2943 /* should accept both names and numeric values, only numeric right now */
2944 struct modattr *extractmodattr(char *nameval) {
2945     int name = 0;
2946     char *s, *t;
2947     struct modattr *m;
2948
2949     if (!strncasecmp(nameval, "User-Name:/", 11)) {
2950         s = nameval + 11;
2951         name = 1;
2952     } else {
2953         s = strchr(nameval, ':');
2954         name = atoi(nameval);
2955         if (!s || name < 1 || name > 255 || s[1] != '/')
2956             return NULL;
2957         s += 2;
2958     }
2959     /* regexp, remove optional trailing / if present */
2960     if (s[strlen(s) - 1] == '/')
2961         s[strlen(s) - 1] = '\0';
2962
2963     t = strchr(s, '/');
2964     if (!t)
2965         return NULL;
2966     *t = '\0';
2967     t++;
2968
2969     m = malloc(sizeof(struct modattr));
2970     if (!m) {
2971         debug(DBG_ERR, "malloc failed");
2972         return NULL;
2973     }
2974     m->t = name;
2975
2976     m->replacement = stringcopy(t, 0);
2977     if (!m->replacement) {
2978         free(m);
2979         debug(DBG_ERR, "malloc failed");
2980         return NULL;
2981     }
2982         
2983     m->regex = malloc(sizeof(regex_t));
2984     if (!m->regex) {
2985         free(m->replacement);
2986         free(m);
2987         debug(DBG_ERR, "malloc failed");
2988         return NULL;
2989     }
2990     
2991     if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2992         free(m->regex);
2993         free(m->replacement);
2994         free(m);
2995         debug(DBG_ERR, "failed to compile regular expression %s", s);
2996         return NULL;
2997     }
2998
2999     return m;
3000 }
3001
3002 struct rewrite *getrewrite(char *alt1, char *alt2) {
3003     struct rewrite *r;
3004
3005     if ((r = hash_read(rewriteconfs,  alt1, strlen(alt1))))
3006         return r;
3007     if ((r = hash_read(rewriteconfs,  alt2, strlen(alt2))))
3008         return r;
3009     return NULL;
3010 }
3011
3012 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
3013     struct rewrite *rewrite = NULL;
3014     int i, n;
3015     uint8_t *rma = NULL;
3016     uint32_t *p, *rmva = NULL;
3017     struct list *adda = NULL, *moda = NULL;
3018     struct attribute *a;
3019     struct modattr *m;
3020     
3021     if (rmattrs) {
3022         for (n = 0; rmattrs[n]; n++);
3023         rma = calloc(n + 1, sizeof(uint8_t));
3024         if (!rma)
3025             debugx(1, DBG_ERR, "malloc failed");
3026     
3027         for (i = 0; i < n; i++) {
3028             if (!(rma[i] = attrname2val(rmattrs[i])))
3029                 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
3030             free(rmattrs[i]);
3031         }
3032         free(rmattrs);
3033         rma[i] = 0;
3034     }
3035     
3036     if (rmvattrs) {
3037         for (n = 0; rmvattrs[n]; n++);
3038         rmva = calloc(2 * n + 1, sizeof(uint32_t));
3039         if (!rmva)
3040             debugx(1, DBG_ERR, "malloc failed");
3041     
3042         for (p = rmva, i = 0; i < n; i++, p += 2) {
3043             if (!vattrname2val(rmvattrs[i], p, p + 1))
3044                 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
3045             free(rmvattrs[i]);
3046         }
3047         free(rmvattrs);
3048         *p = 0;
3049     }
3050     
3051     if (addattrs) {
3052         adda = list_create();
3053         if (!adda)
3054             debugx(1, DBG_ERR, "malloc failed");
3055         for (i = 0; addattrs[i]; i++) {
3056             a = extractattr(addattrs[i]);
3057             if (!a)
3058                 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
3059             free(addattrs[i]);
3060             if (!list_push(adda, a))
3061                 debugx(1, DBG_ERR, "malloc failed");
3062         }
3063         free(addattrs);
3064     }
3065
3066     if (modattrs) {
3067         moda = list_create();
3068         if (!moda)
3069             debugx(1, DBG_ERR, "malloc failed");
3070         for (i = 0; modattrs[i]; i++) {
3071             m = extractmodattr(modattrs[i]);
3072             if (!m)
3073                 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
3074             free(modattrs[i]);
3075             if (!list_push(moda, m))
3076                 debugx(1, DBG_ERR, "malloc failed");
3077         }
3078         free(modattrs);
3079     }
3080         
3081     if (rma || rmva || adda || moda) {
3082         rewrite = malloc(sizeof(struct rewrite));
3083         if (!rewrite)
3084             debugx(1, DBG_ERR, "malloc failed");
3085         rewrite->removeattrs = rma;
3086         rewrite->removevendorattrs = rmva;
3087         rewrite->addattrs = adda;
3088         rewrite->modattrs = moda;
3089     }
3090     
3091     if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
3092         debugx(1, DBG_ERR, "malloc failed");
3093     debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3094 }
3095
3096 void freeclsrvconf(struct clsrvconf *conf) {
3097     free(conf->name);
3098     free(conf->host);
3099     free(conf->port);
3100     free(conf->secret);
3101     free(conf->tls);
3102     free(conf->matchcertattr);
3103     if (conf->certcnregex)
3104         regfree(conf->certcnregex);
3105     if (conf->certuriregex)
3106         regfree(conf->certuriregex);
3107     free(conf->confrewritein);
3108     free(conf->confrewriteout);
3109     if (conf->rewriteusername) {
3110         if (conf->rewriteusername->regex)
3111             regfree(conf->rewriteusername->regex);
3112         free(conf->rewriteusername->replacement);
3113         free(conf->rewriteusername);
3114     }
3115     free(conf->dynamiclookupcommand);
3116     free(conf->rewritein);
3117     free(conf->rewriteout);
3118     if (conf->addrinfo)
3119         freeaddrinfo(conf->addrinfo);
3120     /* not touching ssl_ctx, clients and servers */
3121     free(conf);
3122 }
3123
3124 int mergeconfstring(char **dst, char **src) {
3125     char *t;
3126     
3127     if (*src) {
3128         *dst = *src;
3129         *src = NULL;
3130         return 1;
3131     }
3132     if (*dst) {
3133         t = stringcopy(*dst, 0);
3134         if (!t) {
3135             debug(DBG_ERR, "malloc failed");
3136             return 0;
3137         }
3138         *dst = t;
3139     }
3140     return 1;
3141 }
3142
3143 /* assumes dst is a shallow copy */
3144 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3145     if (!mergeconfstring(&dst->name, &src->name) ||
3146         !mergeconfstring(&dst->host, &src->host) ||
3147         !mergeconfstring(&dst->port, &src->port) ||
3148         !mergeconfstring(&dst->secret, &src->secret) ||
3149         !mergeconfstring(&dst->tls, &src->tls) ||
3150         !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3151         !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
3152         !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
3153         !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3154         return 0;
3155     if (src->pdef)
3156         dst->pdef = src->pdef;
3157     dst->statusserver = src->statusserver;
3158     dst->certnamecheck = src->certnamecheck;
3159     if (src->retryinterval != 255)
3160         dst->retryinterval = src->retryinterval;
3161     if (src->retrycount != 255)
3162         dst->retrycount = src->retrycount;
3163     return 1;
3164 }
3165
3166 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3167     struct clsrvconf *conf;
3168     char *conftype = NULL, *rewriteinalias = NULL;
3169     
3170     debug(DBG_DBG, "confclient_cb called for %s", block);
3171
3172     conf = malloc(sizeof(struct clsrvconf));
3173     if (!conf || !list_push(clconfs, conf))
3174         debugx(1, DBG_ERR, "malloc failed");
3175     memset(conf, 0, sizeof(struct clsrvconf));
3176     conf->certnamecheck = 1;
3177     
3178     if (!getgenericconfig(cf, block,
3179                      "type", CONF_STR, &conftype,
3180                      "host", CONF_STR, &conf->host,
3181                      "secret", CONF_STR, &conf->secret,
3182                      "tls", CONF_STR, &conf->tls,
3183                      "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3184                      "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3185                      "rewrite", CONF_STR, &rewriteinalias,
3186                      "rewriteIn", CONF_STR, &conf->confrewritein,
3187                      "rewriteOut", CONF_STR, &conf->confrewriteout,
3188                      "rewriteattribute", CONF_STR, &conf->confrewriteusername,
3189                      NULL
3190                           ))
3191         debugx(1, DBG_ERR, "configuration error");
3192     
3193     conf->name = stringcopy(val, 0);
3194     if (!conf->host)
3195         conf->host = stringcopy(val, 0);
3196     if (!conf->name || !conf->host)
3197         debugx(1, DBG_ERR, "malloc failed");
3198         
3199     if (!conftype)
3200         debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3201     conf->type = protoname2int(conftype);
3202     conf->pdef = &protodefs[conf->type];
3203     if (!conf->pdef->name)
3204         debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3205     free(conftype);
3206     
3207     if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3208         conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultclient", "default");
3209         if (!conf->ssl_ctx)
3210             debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3211         if (conf->matchcertattr && !addmatchcertattr(conf))
3212             debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3213     }
3214
3215     if (!conf->confrewritein)
3216         conf->confrewritein = rewriteinalias;
3217     else
3218         free(rewriteinalias);
3219     conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
3220     if (conf->confrewriteout)
3221         conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3222     
3223     if (conf->confrewriteusername) {
3224         conf->rewriteusername = extractmodattr(conf->confrewriteusername);
3225         if (!conf->rewriteusername)
3226             debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3227     }
3228     
3229     if (!resolvepeer(conf, 0))
3230         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3231     
3232     if (!conf->secret) {
3233         if (!conf->pdef->secretdefault)
3234             debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3235         conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3236         if (!conf->secret)
3237             debugx(1, DBG_ERR, "malloc failed");
3238     }
3239     return 1;
3240 }
3241
3242 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3243     if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3244         conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultserver", "default");
3245         if (!conf->ssl_ctx) {
3246             debug(DBG_ERR, "error in block %s, no tls context defined", block);
3247             return 0;
3248         }
3249         if (conf->matchcertattr && !addmatchcertattr(conf)) {
3250             debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3251             return 0;
3252         }
3253     }
3254
3255     if (!conf->port) {
3256         conf->port = stringcopy(conf->pdef->portdefault, 0);
3257         if (!conf->port) {
3258             debug(DBG_ERR, "malloc failed");
3259             return 0;
3260         }
3261     }
3262     
3263     if (conf->retryinterval == 255)
3264         conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3265     if (conf->retrycount == 255)
3266         conf->retrycount = protodefs[conf->type].retrycountdefault;
3267     
3268     conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
3269     if (conf->confrewriteout)
3270         conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3271
3272     if (!conf->secret) {
3273         if (!conf->pdef->secretdefault) {
3274             debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3275             return 0;
3276         }
3277         conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3278         if (!conf->secret) {
3279             debug(DBG_ERR, "malloc failed");
3280             return 0;
3281         }
3282     }
3283     
3284     if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3285         debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3286         return 0;
3287     }
3288     return 1;
3289 }
3290                         
3291 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3292     struct clsrvconf *conf, *resconf;
3293     char *conftype = NULL, *rewriteinalias = NULL;
3294     long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3295     
3296     debug(DBG_DBG, "confserver_cb called for %s", block);
3297
3298     conf = malloc(sizeof(struct clsrvconf));
3299     if (!conf) {
3300         debug(DBG_ERR, "malloc failed");
3301         return 0;
3302     }
3303     memset(conf, 0, sizeof(struct clsrvconf));
3304     resconf = (struct clsrvconf *)arg;
3305     if (resconf) {
3306         conf->statusserver = resconf->statusserver;
3307         conf->certnamecheck = resconf->certnamecheck;
3308     } else
3309         conf->certnamecheck = 1;
3310
3311     if (!getgenericconfig(cf, block,
3312                           "type", CONF_STR, &conftype,
3313                           "host", CONF_STR, &conf->host,
3314                           "port", CONF_STR, &conf->port,
3315                           "secret", CONF_STR, &conf->secret,
3316                           "tls", CONF_STR, &conf->tls,
3317                           "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3318                           "rewrite", CONF_STR, &rewriteinalias,
3319                           "rewriteIn", CONF_STR, &conf->confrewritein,
3320                           "rewriteOut", CONF_STR, &conf->confrewriteout,
3321                           "StatusServer", CONF_BLN, &conf->statusserver,
3322                           "RetryInterval", CONF_LINT, &retryinterval,
3323                           "RetryCount", CONF_LINT, &retrycount,
3324                           "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3325                           "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3326                           NULL
3327                           )) {
3328         debug(DBG_ERR, "configuration error");
3329         goto errexit;
3330     }
3331     
3332     conf->name = stringcopy(val, 0);
3333     if (!conf->name) {
3334         debug(DBG_ERR, "malloc failed");
3335         goto errexit;
3336     }
3337     if (!conf->host) {
3338         conf->host = stringcopy(val, 0);
3339         if (!conf->host) {
3340             debug(DBG_ERR, "malloc failed");
3341             goto errexit;
3342         }
3343     }
3344
3345     if (!conftype)
3346         debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3347     conf->type = protoname2int(conftype);
3348     conf->pdef = &protodefs[conf->type];
3349     if (!conf->pdef->name) {
3350         debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3351         goto errexit;
3352     }
3353     free(conftype);
3354     conftype = NULL;
3355
3356     if (!conf->confrewritein)
3357         conf->confrewritein = rewriteinalias;
3358     else
3359         free(rewriteinalias);
3360     rewriteinalias = NULL;
3361
3362     if (retryinterval != LONG_MIN) {
3363         if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3364             debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3365             goto errexit;
3366         }
3367         conf->retryinterval = (uint8_t)retryinterval;
3368     } else
3369         conf->retryinterval = 255;
3370     
3371     if (retrycount != LONG_MIN) {
3372         if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3373             debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3374             goto errexit;
3375         }
3376         conf->retrycount = (uint8_t)retrycount;
3377     } else
3378         conf->retrycount = 255;
3379     
3380     if (resconf) {
3381         if (!mergesrvconf(resconf, conf))
3382             goto errexit;
3383         free(conf);
3384         conf = resconf;
3385         if (conf->dynamiclookupcommand) {
3386             free(conf->dynamiclookupcommand);
3387             conf->dynamiclookupcommand = NULL;
3388         }
3389     }
3390
3391     if (resconf || !conf->dynamiclookupcommand) {
3392         if (!compileserverconfig(conf, block))
3393             goto errexit;
3394     }
3395     
3396     if (resconf)
3397         return 1;
3398         
3399     if (!list_push(srvconfs, conf)) {
3400         debug(DBG_ERR, "malloc failed");
3401         goto errexit;
3402     }
3403     return 1;
3404
3405  errexit:
3406     free(conftype);
3407     free(rewriteinalias);
3408     freeclsrvconf(conf);
3409     return 0;
3410 }
3411
3412 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3413     char **servers = NULL, **accservers = NULL, *msg = NULL;
3414     uint8_t accresp = 0;
3415     
3416     debug(DBG_DBG, "confrealm_cb called for %s", block);
3417     
3418     if (!getgenericconfig(cf, block,
3419                      "server", CONF_MSTR, &servers,
3420                      "accountingServer", CONF_MSTR, &accservers,
3421                      "ReplyMessage", CONF_STR, &msg,
3422                      "AccountingResponse", CONF_BLN, &accresp,
3423                      NULL
3424                           ))
3425         debugx(1, DBG_ERR, "configuration error");
3426
3427     addrealm(realms, val, servers, accservers, msg, accresp);
3428     return 1;
3429 }
3430
3431 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3432     struct tls *conf;
3433     
3434     debug(DBG_DBG, "conftls_cb called for %s", block);
3435     
3436     conf = malloc(sizeof(struct tls));
3437     if (!conf) {
3438         debug(DBG_ERR, "conftls_cb: malloc failed");
3439         return 0;
3440     }
3441     memset(conf, 0, sizeof(struct tls));
3442     
3443     if (!getgenericconfig(cf, block,
3444                      "CACertificateFile", CONF_STR, &conf->cacertfile,
3445                      "CACertificatePath", CONF_STR, &conf->cacertpath,
3446                      "CertificateFile", CONF_STR, &conf->certfile,
3447                      "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3448                      "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3449                      "CRLCheck", CONF_BLN, &conf->crlcheck,
3450                      NULL
3451                           )) {
3452         debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3453         goto errexit;
3454     }
3455     if (!conf->certfile || !conf->certkeyfile) {
3456         debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3457         goto errexit;
3458     }
3459     if (!conf->cacertfile && !conf->cacertpath) {
3460         debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3461         goto errexit;
3462     }
3463
3464     conf->name = stringcopy(val, 0);
3465     if (!conf->name) {
3466         debug(DBG_ERR, "conftls_cb: malloc failed");
3467         goto errexit;
3468     }
3469
3470     if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
3471         debug(DBG_ERR, "conftls_cb: malloc failed");
3472         goto errexit;
3473     }
3474             
3475     debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3476     return 1;
3477
3478  errexit:
3479     free(conf->cacertfile);
3480     free(conf->cacertpath);
3481     free(conf->certfile);
3482     free(conf->certkeyfile);
3483     free(conf->certkeypwd);
3484     free(conf);
3485     return 0;
3486 }
3487
3488 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3489     char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3490     
3491     debug(DBG_DBG, "confrewrite_cb called for %s", block);
3492     
3493     if (!getgenericconfig(cf, block,
3494                      "removeAttribute", CONF_MSTR, &rmattrs,
3495                      "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3496                      "addAttribute", CONF_MSTR, &addattrs,
3497                      "modifyAttribute", CONF_MSTR, &modattrs,
3498                      NULL
3499                           ))
3500         debugx(1, DBG_ERR, "configuration error");
3501     addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3502     return 1;
3503 }
3504
3505 void getmainconfig(const char *configfile) {
3506     long int loglevel = LONG_MIN;
3507     struct gconffile *cfs;
3508
3509     cfs = openconfigfile(configfile);
3510     memset(&options, 0, sizeof(options));
3511     
3512     clconfs = list_create();
3513     if (!clconfs)
3514         debugx(1, DBG_ERR, "malloc failed");
3515     
3516     srvconfs = list_create();
3517     if (!srvconfs)
3518         debugx(1, DBG_ERR, "malloc failed");
3519     
3520     realms = list_create();
3521     if (!realms)
3522         debugx(1, DBG_ERR, "malloc failed");    
3523  
3524     tlsconfs = hash_create();
3525     if (!tlsconfs)
3526         debugx(1, DBG_ERR, "malloc failed");
3527     
3528     rewriteconfs = hash_create();
3529     if (!rewriteconfs)
3530         debugx(1, DBG_ERR, "malloc failed");    
3531  
3532     if (!getgenericconfig(&cfs, NULL,
3533                           "ListenUDP", CONF_MSTR, &options.listenudp,
3534                           "ListenTCP", CONF_MSTR, &options.listentcp,
3535                           "ListenTLS", CONF_MSTR, &options.listentls,
3536                           "ListenDTLS", CONF_MSTR, &options.listendtls,
3537                           "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
3538                           "SourceUDP", CONF_STR, &options.sourceudp,
3539                           "SourceTCP", CONF_STR, &options.sourcetcp,
3540                           "SourceTLS", CONF_STR, &options.sourcetls,
3541                           "SourceDTLS", CONF_STR, &options.sourcedtls,
3542                           "LogLevel", CONF_LINT, &loglevel,
3543                           "LogDestination", CONF_STR, &options.logdestination,
3544                           "LoopPrevention", CONF_BLN, &options.loopprevention,
3545                           "Client", CONF_CBK, confclient_cb, NULL,
3546                           "Server", CONF_CBK, confserver_cb, NULL,
3547                           "Realm", CONF_CBK, confrealm_cb, NULL,
3548                           "TLS", CONF_CBK, conftls_cb, NULL,
3549                           "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3550                           NULL
3551                           ))
3552         debugx(1, DBG_ERR, "configuration error");
3553     
3554     if (loglevel != LONG_MIN) {
3555         if (loglevel < 1 || loglevel > 4)
3556             debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3557         options.loglevel = (uint8_t)loglevel;
3558     }
3559 }
3560
3561 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3562     int c;
3563
3564     while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3565         switch (c) {
3566         case 'c':
3567             *configfile = optarg;
3568             break;
3569         case 'd':
3570             if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3571                 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3572             *loglevel = *optarg - '0';
3573             break;
3574         case 'f':
3575             *foreground = 1;
3576             break;
3577         case 'p':
3578             *pretend = 1;
3579             break;
3580         case 'v':
3581                 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3582         default:
3583             goto usage;
3584         }
3585     }
3586     if (!(argc - optind))
3587         return;
3588
3589  usage:
3590     debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3591 }
3592
3593 #ifdef SYS_SOLARIS9
3594 int daemon(int a, int b) {
3595     int i;
3596
3597     if (fork())
3598         exit(0);
3599
3600     setsid();
3601
3602     for (i = 0; i < 3; i++) {
3603         close(i);
3604         open("/dev/null", O_RDWR);
3605     }
3606     return 1;
3607 }
3608 #endif
3609
3610 void *sighandler(void *arg) {
3611     sigset_t sigset;
3612     int sig;
3613
3614     for(;;) {
3615         sigemptyset(&sigset);
3616         sigaddset(&sigset, SIGPIPE);
3617         sigwait(&sigset, &sig);
3618         /* only get SIGPIPE right now, so could simplify below code */
3619         switch (sig) {
3620         case 0:
3621             /* completely ignoring this */
3622             break;
3623         case SIGPIPE:
3624             debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3625             break;
3626         default:
3627             debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3628         }
3629     }
3630 }
3631
3632 int main(int argc, char **argv) {
3633     pthread_t sigth;
3634     sigset_t sigset;
3635     struct list_node *entry;
3636     uint8_t foreground = 0, pretend = 0, loglevel = 0;
3637     char *configfile = NULL;
3638     struct clsrvconf *srvconf;
3639     int i;
3640     
3641     debug_init("radsecproxy");
3642     debug_set_level(DEBUG_LEVEL);
3643     
3644     getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3645     if (loglevel)
3646         debug_set_level(loglevel);
3647     getmainconfig(configfile ? configfile : CONFIG_MAIN);
3648     if (loglevel)
3649         options.loglevel = loglevel;
3650     else if (options.loglevel)
3651         debug_set_level(options.loglevel);
3652     if (!foreground)
3653         debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3654     free(options.logdestination);
3655
3656     if (!list_first(clconfs))
3657         debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3658     if (!list_first(realms))
3659         debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3660
3661     if (pretend)
3662         debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3663
3664     if (!foreground && (daemon(0, 0) < 0))
3665         debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3666     
3667     debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3668
3669     sigemptyset(&sigset);
3670     /* exit on all but SIGPIPE, ignore more? */
3671     sigaddset(&sigset, SIGPIPE);
3672     pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3673     pthread_create(&sigth, NULL, sighandler, NULL);
3674
3675     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3676         srvconf = (struct clsrvconf *)entry->data;
3677         if (srvconf->dynamiclookupcommand)
3678             continue;
3679         if (!addserver(srvconf))
3680             debugx(1, DBG_ERR, "failed to add server");
3681         if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3682                            (void *)(srvconf->servers)))
3683             debugx(1, DBG_ERR, "pthread_create failed");
3684     }
3685     /* srcprotores for UDP no longer needed */
3686     if (srcprotores[RAD_UDP]) {
3687         freeaddrinfo(srcprotores[RAD_UDP]);
3688         srcprotores[RAD_UDP] = NULL;
3689     }
3690
3691     for (i = 0; protodefs[i].name; i++)
3692         if (protodefs[i].initextra)
3693             protodefs[i].initextra();
3694     
3695     if (find_clconf_type(RAD_TCP, NULL))
3696         createlisteners(RAD_TCP, options.listentcp);
3697     
3698     if (find_clconf_type(RAD_TLS, NULL))
3699         createlisteners(RAD_TLS, options.listentls);
3700     
3701     if (find_clconf_type(RAD_DTLS, NULL))
3702         createlisteners(RAD_DTLS, options.listendtls);
3703     
3704     if (find_clconf_type(RAD_UDP, NULL)) {
3705         createlisteners(RAD_UDP, options.listenudp);
3706         if (options.listenaccudp)
3707             createlisteners(RAD_UDP, options.listenaccudp);
3708     }
3709     
3710     /* just hang around doing nothing, anything to do here? */
3711     for (;;)
3712         sleep(1000);
3713 }