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