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