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