moved null client check to after status server
[libradsec.git] / radsecproxy.c
1 /*
2  * Copyright (C) 2006-2008 Stig Venaas <venaas@uninett.no>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  */
8
9 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
10  *              rd is responsible for init and launching wr
11  * For TLS there is a server instance that launches tlsserverrd for each TLS peer
12  *          each tlsserverrd launches tlsserverwr
13  * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
14  *          for init and launching rd
15  *
16  * serverrd will receive a request, processes it and puts it in the requestq of
17  *          the appropriate clientwr
18  * clientwr monitors its requestq and sends requests
19  * clientrd looks for responses, processes them and puts them in the replyq of
20  *          the peer the request came from
21  * serverwr monitors its reply and sends replies
22  *
23  * In addition to the main thread, we have:
24  * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
25  * If TLS peers are configured, there will initially be 2 * #peers TLS threads
26  * For each TLS peer connecting to us there will be 2 more TLS threads
27  *       This is only for connected peers
28  * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
29  *          1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
30 */
31
32 #include <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(10);
810         } else if (elapsed < 5)
811             sleep(10);
812         else if (elapsed < 300) {
813             debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
814             sleep(elapsed);
815         } else if (elapsed < 100000) {
816             debug(DBG_INFO, "tlsconnect: sleeping %ds", 600);
817             sleep(600);
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;
1669     
1670     for (entry = list_first(realm->srvconfs); entry; entry = list_next(entry)) {
1671         server = ((struct clsrvconf *)entry->data)->servers;
1672         if (!server->connectionok)
1673             continue;
1674         if (!server->loststatsrv)
1675             return server;
1676         if (!best) {
1677             best = server;
1678             continue;
1679         }
1680         if (server->loststatsrv < best->loststatsrv)
1681             best = server;
1682     }
1683     return best;
1684 }
1685
1686 void radsrv(struct request *rq) {
1687     uint8_t code, id, *auth, *attrs, *attr;
1688     uint16_t len;
1689     struct server *to = NULL;
1690     char username[256];
1691     unsigned char newauth[16];
1692     struct realm *realm = NULL;
1693     
1694     code = *(uint8_t *)rq->buf;
1695     id = *(uint8_t *)(rq->buf + 1);
1696     len = RADLEN(rq->buf);
1697     auth = (uint8_t *)(rq->buf + 4);
1698
1699     debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1700     
1701     if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1702         debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1703         freerqdata(rq);
1704         return;
1705     }
1706
1707     len -= 20;
1708     attrs = rq->buf + 20;
1709
1710     if (!attrvalidate(attrs, len)) {
1711         debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1712         freerqdata(rq);
1713         return;
1714     }
1715
1716     attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1717     if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
1718         debug(DBG_WARN, "radsrv: message authentication failed");
1719         freerqdata(rq);
1720         return;
1721     }
1722
1723     if (code != RAD_Access_Request) {
1724         switch (code) {
1725         case RAD_Accounting_Request:
1726             /* when forwarding accounting, also filter attributes, call removeattrs(rq) */
1727             acclog(attrs, len, rq->from->conf->host);
1728             respondaccounting(rq);
1729             break;
1730         case RAD_Status_Server:
1731             respondstatusserver(rq);
1732             break;
1733         }
1734         freerqdata(rq);
1735         return;
1736     }
1737
1738     /* code == RAD_Access_Request */
1739     if (rq->from->conf->rewrite) {
1740         dorewrite(rq->buf, rq->from->conf->rewrite);
1741         len = RADLEN(rq->buf) - 20;
1742     }
1743     
1744     attr = attrget(attrs, len, RAD_Attr_User_Name);
1745     if (!attr) {
1746         debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1747         freerqdata(rq);
1748         return;
1749     }
1750     memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1751     username[ATTRVALLEN(attr)] = '\0';
1752
1753     if (rq->from->conf->rewriteattrregex) {
1754         if (!rewriteusername(rq, username)) {
1755             debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1756             freerqdata(rq);
1757             return;
1758         }
1759         len = RADLEN(rq->buf) - 20;
1760         auth = (uint8_t *)(rq->buf + 4);
1761         attrs = rq->buf + 20;
1762     }
1763
1764     if (rq->origusername)
1765         debug(DBG_DBG, "Access Request with username: %s (originally %s)", username, rq->origusername);
1766     else
1767         debug(DBG_DBG, "Access Request with username: %s", username);
1768         
1769     realm = id2realm(username, strlen(username));
1770     if (!realm) {
1771         debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1772         freerqdata(rq);
1773         return;
1774     }
1775         
1776     to = realm2server(realm);
1777     if (to && rqinqueue(to, rq->from, id)) {
1778         debug(DBG_INFO, "radsrv: already got request from host %s with id %d, ignoring", rq->from->conf->host, id);
1779         freerqdata(rq);
1780         return;
1781     }
1782
1783     if (!to) {
1784         if (realm->message) {
1785             debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, username);
1786             respondreject(rq, realm->message);
1787         }
1788         freerqdata(rq);
1789         return;
1790     }
1791     
1792     if (!RAND_bytes(newauth, 16)) {
1793         debug(DBG_WARN, "radsrv: failed to generate random auth");
1794         freerqdata(rq);
1795         return;
1796     }
1797
1798 #ifdef DEBUG
1799     printfchars(NULL, "auth", "%02x ", auth, 16);
1800 #endif
1801
1802     attr = attrget(attrs, len, RAD_Attr_User_Password);
1803     if (attr) {
1804         debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1805         if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1806             freerqdata(rq);
1807             return;
1808         }
1809     }
1810     
1811     attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1812     if (attr) {
1813         debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1814         if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1815             freerqdata(rq);
1816             return;
1817         }
1818     }
1819
1820     rq->origid = id;
1821     memcpy(rq->origauth, auth, 16);
1822     memcpy(auth, newauth, 16);
1823     sendrq(to, rq);
1824 }
1825
1826 int replyh(struct server *server, unsigned char *buf) {
1827     struct client *from;
1828     struct request *rq;
1829     int i, len, sublen;
1830     unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
1831     struct sockaddr_storage fromsa;
1832     char tmp[256];
1833     
1834     server->connectionok = 1;
1835     server->loststatsrv = 0;
1836         
1837     i = buf[1]; /* i is the id */
1838
1839     switch (*buf) {
1840     case RAD_Access_Accept:
1841         debug(DBG_DBG, "got Access Accept with id %d", i);
1842         break;
1843     case RAD_Access_Reject:
1844         debug(DBG_DBG, "got Access Reject with id %d", i);
1845         break;
1846     case RAD_Access_Challenge:
1847         debug(DBG_DBG, "got Access Challenge with id %d", i);
1848         break;
1849     default:
1850         debug(DBG_INFO, "replyh: discarding, only accept access accept, access reject and access challenge messages");
1851         return 0;
1852     }
1853
1854     rq = server->requests + i;
1855
1856     pthread_mutex_lock(&server->newrq_mutex);
1857     if (!rq->buf || !rq->tries) {
1858         pthread_mutex_unlock(&server->newrq_mutex);
1859         debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
1860         return 0;
1861     }
1862
1863     if (rq->received) {
1864         pthread_mutex_unlock(&server->newrq_mutex);
1865         debug(DBG_INFO, "replyh: already received, ignoring reply");
1866         return 0;
1867     }
1868         
1869     if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
1870         pthread_mutex_unlock(&server->newrq_mutex);
1871         debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
1872         return 0;
1873     }
1874         
1875     len = RADLEN(buf) - 20;
1876     attrs = buf + 20;
1877
1878     if (!attrvalidate(attrs, len)) {
1879         pthread_mutex_unlock(&server->newrq_mutex);
1880         debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
1881         return 0;
1882     }
1883         
1884     /* Message Authenticator */
1885     messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1886     if (messageauth) {
1887         if (ATTRVALLEN(messageauth) != 16) {
1888             pthread_mutex_unlock(&server->newrq_mutex);
1889             debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
1890             return 0;
1891         }
1892         memcpy(tmp, buf + 4, 16);
1893         memcpy(buf + 4, rq->buf + 4, 16);
1894         if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
1895             pthread_mutex_unlock(&server->newrq_mutex);
1896             debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
1897             return 0;
1898         }
1899         memcpy(buf + 4, tmp, 16);
1900         debug(DBG_DBG, "replyh: message auth ok");
1901     }
1902         
1903     if (*rq->buf == RAD_Status_Server) {
1904         rq->received = 1;
1905         pthread_mutex_unlock(&server->newrq_mutex);
1906         debug(DBG_INFO, "replyh: got status server response from %s", server->conf->host);
1907         return 0;
1908     }
1909
1910     from = rq->from;
1911     if (!from) {
1912         pthread_mutex_unlock(&server->newrq_mutex);
1913         debug(DBG_INFO, "replyh: client gone, ignoring reply");
1914         return 0;
1915     }
1916         
1917     if (server->conf->rewrite) {
1918         dorewrite(buf, server->conf->rewrite);
1919         len = RADLEN(buf) - 20;
1920     }
1921     
1922     /* MS MPPE */
1923     for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1924         if (ATTRVALLEN(attr) <= 4)
1925             break;
1926             
1927         if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55)  /* 311 == MS */
1928             continue;
1929             
1930         sublen = ATTRVALLEN(attr) - 4;
1931         subattrs = ATTRVAL(attr) + 4;  
1932         if (!attrvalidate(subattrs, sublen) ||
1933             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1934                     rq, server->conf->secret, from->conf->secret) ||
1935             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1936                     rq, server->conf->secret, from->conf->secret))
1937             break;
1938     }
1939     if (attr) {
1940         pthread_mutex_unlock(&server->newrq_mutex);
1941         debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1942         return 0;
1943     }
1944         
1945     if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject) {
1946         attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
1947         /* we know the attribute exists */
1948         memcpy(tmp, ATTRVAL(attr), ATTRVALLEN(attr));
1949         tmp[ATTRVALLEN(attr)] = '\0';
1950         switch (*buf) {
1951         case RAD_Access_Accept:
1952             if (rq->origusername)
1953                 debug(DBG_INFO, "Access Accept for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1954             else
1955                 debug(DBG_INFO, "Access Accept for %s from %s", tmp, server->conf->host);
1956             break;
1957         case RAD_Access_Reject:
1958             if (rq->origusername)
1959                 debug(DBG_INFO, "Access Reject for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1960             else
1961                 debug(DBG_INFO, "Access Reject for %s from %s", tmp, server->conf->host);
1962             break;
1963         }
1964     }
1965         
1966     buf[1] = (char)rq->origid;
1967     memcpy(buf + 4, rq->origauth, 16);
1968 #ifdef DEBUG    
1969     printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1970 #endif
1971
1972     if (rq->origusername) {
1973         username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
1974         if (!username) {
1975             pthread_mutex_unlock(&server->newrq_mutex);
1976             debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1977             return 0;
1978         }
1979         memcpy(username, rq->origusername, strlen(rq->origusername));
1980         len = RADLEN(buf) - 20;
1981         attrs = buf + 20;
1982         if (messageauth)
1983             messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1984     }
1985         
1986     if (messageauth) {
1987         if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
1988             pthread_mutex_unlock(&server->newrq_mutex);
1989             debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
1990             return 0;
1991         }
1992         debug(DBG_DBG, "replyh: computed messageauthattr");
1993     }
1994
1995     if (from->conf->type == 'U')
1996         fromsa = rq->fromsa;
1997     /* once we set received = 1, rq may be reused */
1998     rq->received = 1;
1999
2000     debug(DBG_DBG, "replyh: giving packet back to where it came from");
2001     sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
2002     pthread_mutex_unlock(&server->newrq_mutex);
2003     return 1;
2004 }
2005
2006 void *udpclientrd(void *arg) {
2007     struct server *server;
2008     unsigned char *buf;
2009     int *s = (int *)arg;
2010     
2011     for (;;) {
2012         server = NULL;
2013         buf = radudpget(*s, NULL, &server, NULL);
2014         if (!replyh(server, buf))
2015             free(buf);
2016     }
2017 }
2018
2019 void *tlsclientrd(void *arg) {
2020     struct server *server = (struct server *)arg;
2021     unsigned char *buf;
2022     struct timeval lastconnecttry;
2023     
2024     for (;;) {
2025         /* yes, lastconnecttry is really necessary */
2026         lastconnecttry = server->lastconnecttry;
2027         buf = radtlsget(server->ssl);
2028         if (!buf) {
2029             tlsconnect(server, &lastconnecttry, "clientrd");
2030             continue;
2031         }
2032
2033         if (!replyh(server, buf))
2034             free(buf);
2035     }
2036 }
2037
2038 void *clientwr(void *arg) {
2039     struct server *server = (struct server *)arg;
2040     struct request *rq;
2041     pthread_t tlsclientrdth;
2042     int i;
2043     uint8_t rnd;
2044     struct timeval now, lastsend;
2045     struct timespec timeout;
2046     struct request statsrvrq;
2047     unsigned char statsrvbuf[38];
2048
2049     memset(&timeout, 0, sizeof(struct timespec));
2050     
2051     if (server->conf->statusserver) {
2052         memset(&statsrvrq, 0, sizeof(struct request));
2053         memset(statsrvbuf, 0, sizeof(statsrvbuf));
2054         statsrvbuf[0] = RAD_Status_Server;
2055         statsrvbuf[3] = 38;
2056         statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2057         statsrvbuf[21] = 18;
2058         gettimeofday(&lastsend, NULL);
2059     }
2060     
2061     if (server->conf->type == 'U') {
2062         server->connectionok = 1;
2063     } else {
2064         tlsconnect(server, NULL, "new client");
2065         server->connectionok = 1;
2066         if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server))
2067             debugx(1, DBG_ERR, "clientwr: pthread_create failed");
2068     }
2069     
2070     for (;;) {
2071         pthread_mutex_lock(&server->newrq_mutex);
2072         if (!server->newrq) {
2073             gettimeofday(&now, NULL);
2074             if (server->conf->statusserver) {
2075                 /* random 0-7 seconds */
2076                 RAND_bytes(&rnd, 1);
2077                 rnd /= 32;
2078                 if (!timeout.tv_sec || timeout.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
2079                     timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
2080             }   
2081             if (timeout.tv_sec) {
2082                 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2083                 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2084                 timeout.tv_sec = 0;
2085             } else {
2086                 debug(DBG_DBG, "clientwr: waiting for new request");
2087                 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
2088             }
2089         }
2090         if (server->newrq) {
2091             debug(DBG_DBG, "clientwr: got new request");
2092             server->newrq = 0;
2093         } else
2094             debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2095         pthread_mutex_unlock(&server->newrq_mutex);
2096
2097         for (i = 0; i < MAX_REQUESTS; i++) {
2098             pthread_mutex_lock(&server->newrq_mutex);
2099             while (i < MAX_REQUESTS && !server->requests[i].buf)
2100                 i++;
2101             if (i == MAX_REQUESTS) {
2102                 pthread_mutex_unlock(&server->newrq_mutex);
2103                 break;
2104             }
2105             rq = server->requests + i;
2106
2107             if (rq->received) {
2108                 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2109                 if (rq->buf) {
2110                     debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2111                     freerqdata(rq);
2112                     /* setting this to NULL means that it can be reused */
2113                     rq->buf = NULL;
2114                 }
2115                 pthread_mutex_unlock(&server->newrq_mutex);
2116                 continue;
2117             }
2118             
2119             gettimeofday(&now, NULL);
2120             if (now.tv_sec < rq->expiry.tv_sec) {
2121                 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2122                     timeout.tv_sec = rq->expiry.tv_sec;
2123                 pthread_mutex_unlock(&server->newrq_mutex);
2124                 continue;
2125             }
2126
2127             if (rq->tries == (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
2128                               ? 1 : REQUEST_RETRIES)) {
2129                 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2130                 if (*rq->buf == RAD_Status_Server) {
2131                     debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->conf->host);
2132                     if (server->loststatsrv < 255)
2133                         server->loststatsrv++;
2134                 }
2135                 freerqdata(rq);
2136                 /* setting this to NULL means that it can be reused */
2137                 rq->buf = NULL;
2138                 pthread_mutex_unlock(&server->newrq_mutex);
2139                 continue;
2140             }
2141             pthread_mutex_unlock(&server->newrq_mutex);
2142
2143             rq->expiry.tv_sec = now.tv_sec +
2144                 (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
2145                  ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
2146             if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2147                 timeout.tv_sec = rq->expiry.tv_sec;
2148             rq->tries++;
2149             clientradput(server, server->requests[i].buf);
2150             gettimeofday(&lastsend, NULL);
2151         }
2152         if (server->conf->statusserver) {
2153             gettimeofday(&now, NULL);
2154             if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
2155                 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2156                     debug(DBG_WARN, "clientwr: failed to generate random auth");
2157                     continue;
2158                 }
2159                 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2160                 if (!statsrvrq.buf) {
2161                     debug(DBG_ERR, "clientwr: malloc failed");
2162                     continue;
2163                 }
2164                 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2165                 debug(DBG_DBG, "clientwr: sending status server to %s", server->conf->host);
2166                 lastsend.tv_sec = now.tv_sec;
2167                 sendrq(server, &statsrvrq);
2168             }
2169         }
2170     }
2171 }
2172
2173 void *udpserverwr(void *arg) {
2174     struct replyq *replyq = udp_server_replyq;
2175     struct reply *reply;
2176     
2177     for (;;) {
2178         pthread_mutex_lock(&replyq->mutex);
2179         while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2180             debug(DBG_DBG, "udp server writer, waiting for signal");
2181             pthread_cond_wait(&replyq->cond, &replyq->mutex);
2182             debug(DBG_DBG, "udp server writer, got signal");
2183         }
2184         pthread_mutex_unlock(&replyq->mutex);
2185
2186         if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
2187                    (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2188             debug(DBG_WARN, "sendudp: send failed");
2189         free(reply->buf);
2190         free(reply);
2191     }
2192 }
2193
2194 void *udpserverrd(void *arg) {
2195     struct request rq;
2196     pthread_t udpserverwrth;
2197     struct clsrvconf *listenres;
2198
2199     listenres = resolve_hostport('U', options.listenudp, DEFAULT_UDP_PORT);
2200     if ((udp_server_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2201         debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2202
2203     debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
2204           listenres->host ? listenres->host : "*", listenres->port);
2205     free(listenres);
2206     
2207     if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
2208         debugx(1, DBG_ERR, "pthread_create failed");
2209     
2210     for (;;) {
2211         memset(&rq, 0, sizeof(struct request));
2212         rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
2213         radsrv(&rq);
2214     }
2215 }
2216
2217 void *udpaccserverrd(void *arg) {
2218     struct request rq;
2219     struct clsrvconf *listenres;
2220     
2221     listenres = resolve_hostport('U', options.listenaccudp, DEFAULT_UDP_PORT);
2222     if ((udp_accserver_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2223         debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2224
2225     debug(DBG_WARN, "udpaccserverrd: listening for UDP on %s:%s",
2226           listenres->host ? listenres->host : "*", listenres->port);
2227     free(listenres);
2228     
2229     for (;;) {
2230         memset(&rq, 0, sizeof(struct request));
2231         rq.buf = radudpget(udp_accserver_sock, &rq.from, NULL, &rq.fromsa);
2232         if (*(uint8_t *)rq.buf == RAD_Accounting_Request) {
2233             radsrv(&rq);
2234             continue;
2235         }
2236         debug(DBG_INFO, "udpaccserverrd: got something other than accounting-request, ignoring");
2237         freerqdata(&rq);
2238     }
2239 }
2240
2241 void *tlsserverwr(void *arg) {
2242     int cnt;
2243     unsigned long error;
2244     struct client *client = (struct client *)arg;
2245     struct replyq *replyq;
2246     struct reply *reply;
2247     
2248     debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
2249     replyq = client->replyq;
2250     for (;;) {
2251         pthread_mutex_lock(&replyq->mutex);
2252         while (!list_first(replyq->replies)) {
2253             if (client->ssl) {      
2254                 debug(DBG_DBG, "tls server writer, waiting for signal");
2255                 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2256                 debug(DBG_DBG, "tls server writer, got signal");
2257             }
2258             if (!client->ssl) {
2259                 /* ssl might have changed while waiting */
2260                 pthread_mutex_unlock(&replyq->mutex);
2261                 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2262                 pthread_exit(NULL);
2263             }
2264         }
2265         reply = (struct reply *)list_shift(replyq->replies);
2266         pthread_mutex_unlock(&replyq->mutex);
2267         cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2268         if (cnt > 0)
2269             debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
2270                   cnt, RADLEN(reply->buf));
2271         else
2272             while ((error = ERR_get_error()))
2273                 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2274         free(reply->buf);
2275         free(reply);
2276     }
2277 }
2278
2279 void *tlsserverrd(void *arg) {
2280     struct request rq;
2281     unsigned long error;
2282     int s;
2283     struct client *client = (struct client *)arg;
2284     pthread_t tlsserverwrth;
2285     SSL *ssl;
2286     
2287     debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2288     ssl = client->ssl;
2289
2290     if (SSL_accept(ssl) <= 0) {
2291         while ((error = ERR_get_error()))
2292             debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2293         debug(DBG_ERR, "SSL_accept failed");
2294         goto errexit;
2295     }
2296     if (tlsverifycert(client->ssl, client->conf)) {
2297         if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2298             debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2299             goto errexit;
2300         }
2301         for (;;) {
2302             memset(&rq, 0, sizeof(struct request));
2303             rq.buf = radtlsget(client->ssl);
2304             if (!rq.buf)
2305                 break;
2306             debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2307             rq.from = client;
2308             radsrv(&rq);
2309         }
2310         debug(DBG_ERR, "tlsserverrd: connection lost");
2311         /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2312         client->ssl = NULL;
2313         pthread_mutex_lock(&client->replyq->mutex);
2314         pthread_cond_signal(&client->replyq->cond);
2315         pthread_mutex_unlock(&client->replyq->mutex);
2316         debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2317         pthread_join(tlsserverwrth, NULL);
2318     }
2319     
2320  errexit:
2321     s = SSL_get_fd(ssl);
2322     SSL_free(ssl);
2323     shutdown(s, SHUT_RDWR);
2324     close(s);
2325     debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->conf->host);
2326     removeclientrqs(client);
2327     removeclient(client);
2328     pthread_exit(NULL);
2329 }
2330
2331 int tlslistener() {
2332     pthread_t tlsserverth;
2333     int s, snew;
2334     struct sockaddr_storage from;
2335     size_t fromlen = sizeof(from);
2336     struct clsrvconf *conf;
2337     struct client *client;
2338     struct clsrvconf *listenres;
2339     
2340     listenres = resolve_hostport('T', options.listentcp, DEFAULT_TLS_PORT);
2341     if ((s = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2342         debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
2343     
2344     listen(s, 0);
2345     debug(DBG_WARN, "listening for incoming TCP on %s:%s", listenres->host ? listenres->host : "*", listenres->port);
2346     free(listenres);
2347     
2348     for (;;) {
2349         snew = accept(s, (struct sockaddr *)&from, &fromlen);
2350         if (snew < 0) {
2351             debug(DBG_WARN, "accept failed");
2352             continue;
2353         }
2354         debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2355
2356         conf = find_conf('T', (struct sockaddr *)&from, clconfs, NULL);
2357         if (!conf) {
2358             debug(DBG_WARN, "ignoring request, not a known TLS client");
2359             shutdown(snew, SHUT_RDWR);
2360             close(snew);
2361             continue;
2362         }
2363
2364         client = addclient(conf);
2365
2366         if (!client) {
2367             debug(DBG_WARN, "Failed to create new client instance");
2368             shutdown(snew, SHUT_RDWR);
2369             close(snew);
2370             continue;
2371         }
2372         client->ssl = SSL_new(client->conf->ssl_ctx);
2373         SSL_set_fd(client->ssl, snew);
2374         if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
2375             debug(DBG_ERR, "tlslistener: pthread_create failed");
2376             SSL_free(client->ssl);
2377             removeclient(client);
2378             shutdown(snew, SHUT_RDWR);
2379             close(snew);
2380             continue;
2381         }
2382         pthread_detach(tlsserverth);
2383     }
2384     return 0;
2385 }
2386
2387 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
2388     struct tls *new;
2389     SSL_CTX *ctx;
2390     STACK_OF(X509_NAME) *calist;
2391     int i;
2392     unsigned long error;
2393     
2394     if (!certfile || !certkeyfile)
2395         debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2396
2397     if (!cacertfile && !cacertpath)
2398         debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2399
2400     if (!ssl_locks) {
2401         ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2402         ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2403         for (i = 0; i < CRYPTO_num_locks(); i++) {
2404             ssl_lock_count[i] = 0;
2405             pthread_mutex_init(&ssl_locks[i], NULL);
2406         }
2407         CRYPTO_set_id_callback(ssl_thread_id);
2408         CRYPTO_set_locking_callback(ssl_locking_callback);
2409
2410         SSL_load_error_strings();
2411         SSL_library_init();
2412
2413         while (!RAND_status()) {
2414             time_t t = time(NULL);
2415             pid_t pid = getpid();
2416             RAND_seed((unsigned char *)&t, sizeof(time_t));
2417             RAND_seed((unsigned char *)&pid, sizeof(pid));
2418         }
2419     }
2420     ctx = SSL_CTX_new(TLSv1_method());
2421     if (certkeypwd) {
2422         SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2423         SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2424     }
2425     if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2426         !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2427         !SSL_CTX_check_private_key(ctx) ||
2428         !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2429         while ((error = ERR_get_error()))
2430             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2431         debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2432     }
2433
2434     calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
2435     if (!cacertfile || calist) {
2436         if (cacertpath) {
2437             if (!calist)
2438                 calist = sk_X509_NAME_new_null();
2439             if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
2440                 sk_X509_NAME_free(calist);
2441                 calist = NULL;
2442             }
2443         }
2444     }
2445     if (!calist) {
2446         while ((error = ERR_get_error()))
2447             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2448         debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
2449     }
2450     SSL_CTX_set_client_CA_list(ctx, calist);
2451     
2452     SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2453     SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2454
2455     new = malloc(sizeof(struct tls));
2456     if (!new || !list_push(tlsconfs, new))
2457         debugx(1, DBG_ERR, "malloc failed");
2458
2459     memset(new, 0, sizeof(struct tls));
2460     new->name = stringcopy(value, 0);
2461     if (!new->name)
2462         debugx(1, DBG_ERR, "malloc failed");
2463     new->ctx = ctx;
2464     new->count = 0;
2465     debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2466 }
2467
2468 void tlsfree() {
2469     struct list_node *entry;
2470     struct tls *t;
2471     
2472     for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2473         t = (struct tls *)entry->data;
2474         if (t->name)
2475             free(t->name);
2476         if (!t->count)
2477             SSL_CTX_free(t->ctx);
2478     }
2479     list_destroy(tlsconfs);
2480     tlsconfs = NULL;
2481 }
2482
2483 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2484     struct list_node *entry;
2485     struct tls *t, *t1 = NULL, *t2 = NULL;
2486     
2487     for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2488         t = (struct tls *)entry->data;
2489         if (!strcasecmp(t->name, alt1)) {
2490             t1 = t;
2491             break;
2492         }
2493         if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2494             t2 = t;
2495     }
2496
2497     t = (t1 ? t1 : t2);
2498     if (!t)
2499         return NULL;
2500     t->count++;
2501     return t->ctx;
2502 }
2503
2504 void addrealm(char *value, char **servers, char *message) {
2505     int n;
2506     struct realm *realm;
2507     char *s, *regex = NULL;
2508     struct list_node *entry;
2509     struct clsrvconf *conf;
2510     
2511     if (*value == '/') {
2512         /* regexp, remove optional trailing / if present */
2513         if (value[strlen(value) - 1] == '/')
2514             value[strlen(value) - 1] = '\0';
2515     } else {
2516         /* not a regexp, let us make it one */
2517         if (*value == '*' && !value[1])
2518             regex = stringcopy(".*", 0);
2519         else {
2520             for (n = 0, s = value; *s;)
2521                 if (*s++ == '.')
2522                     n++;
2523             regex = malloc(strlen(value) + n + 3);
2524             if (regex) {
2525                 regex[0] = '@';
2526                 for (n = 1, s = value; *s; s++) {
2527                     if (*s == '.')
2528                         regex[n++] = '\\';
2529                     regex[n++] = *s;
2530                 }
2531                 regex[n++] = '$';
2532                 regex[n] = '\0';
2533             }
2534         }
2535         if (!regex)
2536             debugx(1, DBG_ERR, "malloc failed");
2537         debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2538     }
2539
2540     realm = malloc(sizeof(struct realm));
2541     if (!realm)
2542         debugx(1, DBG_ERR, "malloc failed");
2543     
2544     memset(realm, 0, sizeof(struct realm));
2545     realm->name = stringcopy(value, 0);
2546     if (!realm->name)
2547         debugx(1, DBG_ERR, "malloc failed");
2548     if (message && strlen(message) > 253)
2549         debugx(1, DBG_ERR, "ReplyMessage can be at most 253 bytes");
2550     realm->message = message;
2551     
2552     if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB))
2553         debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2554     if (regex)
2555         free(regex);
2556     
2557     if (servers && *servers) {
2558         realm->srvconfs = list_create();
2559         if (!realm->srvconfs)
2560             debugx(1, DBG_ERR, "malloc failed");
2561         for (n = 0; servers[n]; n++) {
2562             for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2563                 conf = (struct clsrvconf *)entry->data;
2564                 if (!strcasecmp(servers[n], conf->name))
2565                     break;
2566             }
2567             if (!entry)
2568                 debugx(1, DBG_ERR, "addrealm failed, no server %s", servers[n]);
2569             if (!list_push(realm->srvconfs, conf))
2570                 debugx(1, DBG_ERR, "malloc failed");
2571             debug(DBG_DBG, "addrealm: added server %s for realm %s", conf->name, value);
2572         }
2573     } else
2574         realm->srvconfs = NULL;
2575     
2576     if (!list_push(realms, realm))
2577         debugx(1, DBG_ERR, "malloc failed");
2578     debug(DBG_DBG, "addrealm: added realm %s", value);
2579 }
2580
2581 struct gconffile *openconfigfile(const char *filename) {
2582     FILE *f;
2583     char pathname[100], *base = NULL;
2584     struct gconffile *cf = NULL;
2585     
2586     f = pushgconffile(&cf, filename);
2587     if (f) {
2588         debug(DBG_DBG, "reading config file %s", filename);
2589         return cf;
2590     }
2591
2592     if (strlen(filename) + 1 <= sizeof(pathname)) {
2593         /* basename() might modify the string */
2594         strcpy(pathname, filename);
2595         base = basename(pathname);
2596         f = pushgconffile(&cf, base);
2597     }
2598
2599     if (!f)
2600         debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
2601     
2602     debug(DBG_DBG, "reading config file %s", base);
2603     return cf;
2604 }
2605
2606 int addmatchcertattr(struct clsrvconf *conf, char *matchcertattr) {
2607     char *v;
2608     regex_t **r;
2609     
2610     if (strncasecmp(matchcertattr, "CN:/", 4)) {
2611         r = &conf->certcnregex;
2612         v = matchcertattr + 4;
2613     } else if (strncasecmp(matchcertattr, "SubjectAltName:URI:/", 20)) {
2614         r = &conf->certuriregex;
2615         v = matchcertattr + 20;
2616     } else
2617         return 0;
2618     if (!*v)
2619         return 0;
2620     /* regexp, remove optional trailing / if present */
2621     if (v[strlen(v) - 1] == '/')
2622         v[strlen(v) - 1] = '\0';
2623     if (!*v)
2624         return 0;
2625
2626     *r = malloc(sizeof(regex_t));
2627     if (!*r) {
2628         debug(DBG_ERR, "malloc failed");
2629         return 0;
2630     }
2631     if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
2632         free(*r);
2633         *r = NULL;
2634         debug(DBG_ERR, "failed to compile regular expression %s", v);
2635         return 0;
2636     }
2637     return 1;
2638 }
2639
2640 int addrewriteattr(struct clsrvconf *conf, char *rewriteattr) {
2641     char *v, *w;
2642     
2643     v = rewriteattr + 11;
2644     if (strncasecmp(rewriteattr, "User-Name:/", 11) || !*v)
2645         return 0;
2646     /* regexp, remove optional trailing / if present */
2647     if (v[strlen(v) - 1] == '/')
2648         v[strlen(v) - 1] = '\0';
2649
2650     w = strchr(v, '/');
2651     if (!*w)
2652         return 0;
2653     *w = '\0';
2654     w++;
2655     
2656     conf->rewriteattrregex = malloc(sizeof(regex_t));
2657     if (!conf->rewriteattrregex) {
2658         debug(DBG_ERR, "malloc failed");
2659         return 0;
2660     }
2661
2662     conf->rewriteattrreplacement = stringcopy(w, 0);
2663     if (!conf->rewriteattrreplacement) {
2664         free(conf->rewriteattrregex);
2665         conf->rewriteattrregex = NULL;
2666         return 0;
2667     }
2668     
2669     if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
2670         free(conf->rewriteattrregex);
2671         conf->rewriteattrregex = NULL;
2672         free(conf->rewriteattrreplacement);
2673         conf->rewriteattrreplacement = NULL;
2674         debug(DBG_ERR, "failed to compile regular expression %s", v);
2675         return 0;
2676     }
2677
2678     return 1;
2679 }
2680
2681 /* should accept both names and numeric values, only numeric right now */
2682 uint8_t attrname2val(char *attrname) {
2683     int val = 0;
2684     
2685     val = atoi(attrname);
2686     return val > 0 && val < 256 ? val : 0;
2687 }
2688
2689 /* should accept both names and numeric values, only numeric right now */
2690 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2691     char *s;
2692     
2693     *vendor = atoi(attrname);
2694     s = strchr(attrname, ':');
2695     if (!s) {
2696         *type = -1;
2697         return 1;
2698     }
2699     *type = atoi(s + 1);
2700     return *type >= 0 && *type < 256;
2701 }
2702
2703 void rewritefree() {
2704     struct list_node *entry;
2705     struct rewriteconf *r;
2706     
2707     for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
2708         r = (struct rewriteconf *)entry->data;
2709         if (r->name)
2710             free(r->name);
2711         if (!r->count)
2712             free(r->rewrite);
2713     }
2714     list_destroy(rewriteconfs);
2715     rewriteconfs = NULL;
2716 }
2717
2718 struct rewrite *getrewrite(char *alt1, char *alt2) {
2719     struct list_node *entry;
2720     struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
2721     
2722     for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
2723         r = (struct rewriteconf *)entry->data;
2724         if (!strcasecmp(r->name, alt1)) {
2725             r1 = r;
2726             break;
2727         }
2728         if (!r2 && alt2 && !strcasecmp(r->name, alt2))
2729             r2 = r;
2730     }
2731
2732     r = (r1 ? r1 : r2);
2733     if (!r)
2734         return NULL;
2735     r->count++;
2736     return r->rewrite;
2737 }
2738
2739 void addrewrite(char *value, char **attrs, char **vattrs) {
2740     struct rewriteconf *new;
2741     struct rewrite *rewrite = NULL;
2742     int i, n;
2743     uint8_t *a = NULL;
2744     uint32_t *p, *va = NULL;
2745
2746     if (attrs) {
2747         n = 0;
2748         for (; attrs[n]; n++);
2749         a = malloc((n + 1) * sizeof(uint8_t));
2750         if (!a)
2751             debugx(1, DBG_ERR, "malloc failed");
2752     
2753         for (i = 0; i < n; i++)
2754             if (!(a[i] = attrname2val(attrs[i])))
2755                 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
2756         a[i] = 0;
2757     }
2758     
2759     if (vattrs) {
2760         n = 0;
2761         for (; vattrs[n]; n++);
2762         va = malloc((2 * n + 1) * sizeof(uint32_t));
2763         if (!va)
2764             debugx(1, DBG_ERR, "malloc failed");
2765     
2766         for (p = va, i = 0; i < n; i++, p += 2)
2767             if (!vattrname2val(vattrs[i], p, p + 1))
2768                 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
2769         *p = 0;
2770     }
2771     
2772     if (a || va) {
2773         rewrite = malloc(sizeof(struct rewrite));
2774         if (!rewrite)
2775             debugx(1, DBG_ERR, "malloc failed");
2776         rewrite->removeattrs = a;
2777         rewrite->removevendorattrs = va;
2778     }
2779     
2780     new = malloc(sizeof(struct rewriteconf));
2781     if (!new || !list_push(rewriteconfs, new))
2782         debugx(1, DBG_ERR, "malloc failed");
2783
2784     memset(new, 0, sizeof(struct rewriteconf));
2785     new->name = stringcopy(value, 0);
2786     if (!new->name)
2787         debugx(1, DBG_ERR, "malloc failed");
2788         
2789     new->rewrite = rewrite;
2790     debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2791 }
2792
2793 void confclient_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2794     char *type = NULL, *tls = NULL, *matchcertattr = NULL, *rewrite = NULL, *rewriteattr = NULL;
2795     struct clsrvconf *conf;
2796     
2797     debug(DBG_DBG, "confclient_cb called for %s", block);
2798
2799     conf = malloc(sizeof(struct clsrvconf));
2800     if (!conf || !list_push(clconfs, conf))
2801         debugx(1, DBG_ERR, "malloc failed");
2802     memset(conf, 0, sizeof(struct clsrvconf));
2803     
2804     getgenericconfig(cf, block,
2805                      "type", CONF_STR, &type,
2806                      "host", CONF_STR, &conf->host,
2807                      "secret", CONF_STR, &conf->secret,
2808                      "tls", CONF_STR, &tls,
2809                      "matchcertificateattribute", CONF_STR, &matchcertattr,
2810                      "rewrite", CONF_STR, &rewrite,
2811                      "rewriteattribute", CONF_STR, &rewriteattr,
2812                      NULL
2813                      );
2814
2815     /* leave conf->name to be NULL for clients */
2816     if (!conf->host)
2817         conf->host = stringcopy(val, 0);
2818     
2819     if (type && !strcasecmp(type, "udp")) {
2820         conf->type = 'U';
2821         client_udp_count++;
2822     } else if (type && !strcasecmp(type, "tls")) {
2823         conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultclient", "default");
2824         if (!conf->ssl_ctx)
2825             debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2826         if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2827             debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2828         conf->type = 'T';
2829         client_tls_count++;
2830     } else
2831         debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2832     free(type);
2833     if (tls)
2834         free(tls);
2835     if (matchcertattr)
2836         free(matchcertattr);
2837     
2838     conf->rewrite = rewrite ? getrewrite(rewrite, NULL) : getrewrite("defaultclient", "default");
2839     
2840     if (rewriteattr) {
2841         if (!addrewriteattr(conf, rewriteattr))
2842             debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2843         free(rewriteattr);
2844     }
2845     
2846     if (!resolvepeer(conf, 0))
2847         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2848     
2849     if (!conf->secret) {
2850         if (conf->type == 'U')
2851             debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2852         conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2853     }
2854 }
2855
2856 void confserver_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2857     char *type = NULL, *tls = NULL, *matchcertattr = NULL, *statusserver = NULL, *rewrite = NULL;
2858     struct clsrvconf *conf;
2859     
2860     debug(DBG_DBG, "confserver_cb called for %s", block);
2861
2862     conf = malloc(sizeof(struct clsrvconf));
2863     if (!conf || !list_push(srvconfs, conf))
2864         debugx(1, DBG_ERR, "malloc failed");
2865     memset(conf, 0, sizeof(struct clsrvconf));
2866     
2867     getgenericconfig(cf, block,
2868                      "type", CONF_STR, &type,
2869                      "host", CONF_STR, &conf->host,
2870                      "port", CONF_STR, &conf->port,
2871                      "secret", CONF_STR, &conf->secret,
2872                      "tls", CONF_STR, &tls,
2873                      "matchcertificateattribute", CONF_STR, &matchcertattr,
2874                      "rewrite", CONF_STR, &rewrite,
2875                      "StatusServer", CONF_STR, &statusserver,
2876                      NULL
2877                      );
2878
2879     conf->name = stringcopy(val, 0);
2880     if (!conf->host)
2881         conf->host = stringcopy(val, 0);
2882     
2883     if (type && !strcasecmp(type, "udp")) {
2884         conf->type = 'U';
2885         server_udp_count++;
2886         if (!conf->port)
2887             conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
2888     } else if (type && !strcasecmp(type, "tls")) {
2889         conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultserver", "default");
2890         if (!conf->ssl_ctx)
2891             debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2892         if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2893             debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2894         if (!conf->port)
2895             conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
2896         conf->type = 'T';
2897         server_tls_count++;
2898     } else
2899         debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2900     free(type);
2901     if (tls)
2902         free(tls);
2903     if (matchcertattr)
2904         free(matchcertattr);
2905     
2906     conf->rewrite = rewrite ? getrewrite(rewrite, NULL) : getrewrite("defaultserver", "default");
2907     
2908     if (!resolvepeer(conf, 0))
2909         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2910     
2911     if (!conf->secret) {
2912         if (conf->type == 'U')
2913             debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2914         conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2915     }
2916     
2917     if (statusserver) {
2918         if (!strcasecmp(statusserver, "on"))
2919             conf->statusserver = 1;
2920         else if (strcasecmp(statusserver, "off"))
2921             debugx(1, DBG_ERR, "error in block %s, StatusServer is %s, must be on or off", block, statusserver);
2922         free(statusserver);
2923     }
2924 }
2925
2926 void confrealm_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2927     char **servers = NULL, *msg = NULL;
2928     
2929     debug(DBG_DBG, "confrealm_cb called for %s", block);
2930     
2931     getgenericconfig(cf, block,
2932                      "server", CONF_MSTR, &servers,
2933                      "ReplyMessage", CONF_STR, &msg,
2934                      NULL
2935                      );
2936
2937     addrealm(val, servers, msg);
2938     free(servers);
2939 }
2940
2941 void conftls_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2942     char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
2943     
2944     debug(DBG_DBG, "conftls_cb called for %s", block);
2945     
2946     getgenericconfig(cf, block,
2947                      "CACertificateFile", CONF_STR, &cacertfile,
2948                      "CACertificatePath", CONF_STR, &cacertpath,
2949                      "CertificateFile", CONF_STR, &certfile,
2950                      "CertificateKeyFile", CONF_STR, &certkeyfile,
2951                      "CertificateKeyPassword", CONF_STR, &certkeypwd,
2952                      NULL
2953                      );
2954     
2955     tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
2956     free(cacertfile);
2957     free(cacertpath);
2958     free(certfile);
2959     free(certkeyfile);
2960     free(certkeypwd);
2961 }
2962
2963 void confrewrite_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2964     char **attrs = NULL, **vattrs = NULL;
2965     
2966     debug(DBG_DBG, "confrewrite_cb called for %s", block);
2967     
2968     getgenericconfig(cf, block,
2969                      "removeAttribute", CONF_MSTR, &attrs,
2970                      "removeVendorAttribute", CONF_MSTR, &vattrs,
2971                      NULL
2972                      );
2973     addrewrite(val, attrs, vattrs);
2974     free(attrs);
2975     free(vattrs);
2976 }
2977
2978 void getmainconfig(const char *configfile) {
2979     char *loglevel = NULL;
2980     struct gconffile *cfs;
2981
2982     cfs = openconfigfile(configfile);
2983     memset(&options, 0, sizeof(options));
2984     
2985     clconfs = list_create();
2986     if (!clconfs)
2987         debugx(1, DBG_ERR, "malloc failed");
2988     
2989     srvconfs = list_create();
2990     if (!srvconfs)
2991         debugx(1, DBG_ERR, "malloc failed");
2992     
2993     realms = list_create();
2994     if (!realms)
2995         debugx(1, DBG_ERR, "malloc failed");    
2996  
2997     tlsconfs = list_create();
2998     if (!tlsconfs)
2999         debugx(1, DBG_ERR, "malloc failed");
3000     
3001     rewriteconfs = list_create();
3002     if (!rewriteconfs)
3003         debugx(1, DBG_ERR, "malloc failed");    
3004  
3005     getgenericconfig(&cfs, NULL,
3006                      "ListenUDP", CONF_STR, &options.listenudp,
3007                      "ListenTCP", CONF_STR, &options.listentcp,
3008                      "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
3009                      "SourceUDP", CONF_STR, &options.sourceudp,
3010                      "SourceTCP", CONF_STR, &options.sourcetcp,
3011                      "LogLevel", CONF_STR, &loglevel,
3012                      "LogDestination", CONF_STR, &options.logdestination,
3013                      "Client", CONF_CBK, confclient_cb,
3014                      "Server", CONF_CBK, confserver_cb,
3015                      "Realm", CONF_CBK, confrealm_cb,
3016                      "TLS", CONF_CBK, conftls_cb,
3017                      "Rewrite", CONF_CBK, confrewrite_cb,
3018                      NULL
3019                      );
3020     popgconffile(&cfs);
3021     tlsfree();
3022     rewritefree();
3023     
3024     if (loglevel) {
3025         if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
3026             debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
3027         options.loglevel = *loglevel - '0';
3028         free(loglevel);
3029     }
3030 }
3031
3032 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3033     int c;
3034
3035     while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3036         switch (c) {
3037         case 'c':
3038             *configfile = optarg;
3039             break;
3040         case 'd':
3041             if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3042                 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3043             *loglevel = *optarg - '0';
3044             break;
3045         case 'f':
3046             *foreground = 1;
3047             break;
3048         case 'p':
3049             *pretend = 1;
3050             break;
3051         case 'v':
3052                 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3053         default:
3054             goto usage;
3055         }
3056     }
3057     if (!(argc - optind))
3058         return;
3059
3060  usage:
3061     debug(DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3062     exit(1);
3063 }
3064
3065 #ifdef SYS_SOLARIS9
3066 int daemon(int a, int b) {
3067     int i;
3068
3069     if (fork())
3070         exit(0);
3071
3072     setsid();
3073
3074     for (i = 0; i < 3; i++) {
3075         close(i);
3076         open("/dev/null", O_RDWR);
3077     }
3078     return 1;
3079 }
3080 #endif
3081
3082 int main(int argc, char **argv) {
3083     pthread_t udpserverth, udpaccserverth, udpclient4rdth, udpclient6rdth;
3084     struct list_node *entry;
3085     uint8_t foreground = 0, pretend = 0, loglevel = 0;
3086     char *configfile = NULL;
3087     
3088     debug_init("radsecproxy");
3089     debug_set_level(DEBUG_LEVEL);
3090     getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3091     if (loglevel)
3092         debug_set_level(loglevel);
3093     getmainconfig(configfile ? configfile : CONFIG_MAIN);
3094     if (loglevel)
3095         options.loglevel = loglevel;
3096     else if (options.loglevel)
3097         debug_set_level(options.loglevel);
3098     if (foreground)
3099         options.logdestination = NULL;
3100     else {
3101         if (!options.logdestination)
3102             options.logdestination = "x-syslog:///";
3103         debug_set_destination(options.logdestination);
3104     }
3105
3106     if (pretend)
3107         debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3108     
3109     if (!list_first(clconfs))
3110         debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3111     if (!list_first(srvconfs))
3112         debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
3113     if (!list_first(realms))
3114         debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3115
3116     if (!foreground && (daemon(0, 0) < 0))
3117         debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3118     
3119     debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3120
3121     if (client_udp_count) {
3122         udp_server_replyq = newreplyq();
3123         if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
3124             debugx(1, DBG_ERR, "pthread_create failed");
3125         if (options.listenaccudp)
3126             if (pthread_create(&udpaccserverth, NULL, udpaccserverrd, NULL))
3127                 debugx(1, DBG_ERR, "pthread_create failed");
3128     }
3129     
3130     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3131         addserver((struct clsrvconf *)entry->data);
3132         if (pthread_create(&((struct clsrvconf *)entry->data)->servers->clientth, NULL, clientwr,
3133                            (void *)((struct clsrvconf *)entry->data)->servers))
3134             debugx(1, DBG_ERR, "pthread_create failed");
3135     }
3136     /* srcudpres no longer needed, while srctcpres is needed later */
3137     if (srcudpres) {
3138         free(srcudpres);
3139         srcudpres = NULL;
3140     }
3141     if (udp_client4_sock >= 0)
3142         if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
3143             debugx(1, DBG_ERR, "clientwr: pthread_create failed");
3144     if (udp_client6_sock >= 0)
3145         if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
3146             debugx(1, DBG_ERR, "clientwr: pthread_create failed");
3147     
3148     if (client_tls_count)
3149         return tlslistener();
3150     
3151     /* just hang around doing nothing, anything to do here? */
3152     for (;;)
3153         sleep(1000);
3154 }