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