Solaris9 fixes
[radsecproxy.git] / radsecproxy.c
1 /*
2  * Copyright (C) 2006, 2007 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;
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->port);
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->port);
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     if (!client || !client->conf->clients)
440         return;
441
442     list_removedata(client->conf->clients, client);
443     free(client);
444 }
445
446 void addserver(struct clsrvconf *conf) {
447     if (conf->servers)
448         debugx(1, DBG_ERR, "addserver: currently works with just one server per conf");
449     
450     conf->servers = malloc(sizeof(struct server));
451     if (!conf->servers)
452         debugx(1, DBG_ERR, "malloc failed");
453     memset(conf->servers, 0, sizeof(struct server));
454     conf->servers->conf = conf;
455
456     if (conf->type == 'U') {
457         if (!srcudpres)
458             srcudpres = resolve_hostport('U', options.sourceudp, NULL);
459         switch (conf->addrinfo->ai_family) {
460         case AF_INET:
461             if (udp_client4_sock < 0) {
462                 udp_client4_sock = bindtoaddr(srcudpres->addrinfo, AF_INET, 0, 1);
463                 if (udp_client4_sock < 0)
464                     debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
465             }
466             conf->servers->sock = udp_client4_sock;
467             break;
468         case AF_INET6:
469             if (udp_client6_sock < 0) {
470                 udp_client6_sock = bindtoaddr(srcudpres->addrinfo, AF_INET6, 0, 1);
471                 if (udp_client6_sock < 0)
472                     debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
473             }
474             conf->servers->sock = udp_client6_sock;
475             break;
476         default:
477             debugx(1, DBG_ERR, "addserver: unsupported address family");
478         }
479         
480     } else {
481         if (!srctcpres)
482             srctcpres = resolve_hostport('T', options.sourcetcp, NULL);
483         conf->servers->sock = -1;
484     }
485     
486     pthread_mutex_init(&conf->servers->lock, NULL);
487     conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
488     if (!conf->servers->requests)
489         debugx(1, DBG_ERR, "malloc failed");
490     conf->servers->newrq = 0;
491     pthread_mutex_init(&conf->servers->newrq_mutex, NULL);
492     pthread_cond_init(&conf->servers->newrq_cond, NULL);
493 }
494
495 /* exactly one of client and server must be non-NULL */
496 /* should probably take peer list (client(s) or server(s)) as argument instead */
497 /* if *peer == NULL we return who we received from, else require it to be from peer */
498 /* return from in sa if not NULL */
499 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
500     int cnt, len;
501     unsigned char buf[65536], *rad;
502     struct sockaddr_storage from;
503     socklen_t fromlen = sizeof(from);
504     struct clsrvconf *p;
505     struct list_node *node;
506     
507     for (;;) {
508         cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
509         if (cnt == -1) {
510             debug(DBG_WARN, "radudpget: recv failed");
511             continue;
512         }
513         debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
514
515         if (cnt < 20) {
516             debug(DBG_WARN, "radudpget: packet too small");
517             continue;
518         }
519     
520         len = RADLEN(buf);
521         if (len < 20) {
522             debug(DBG_WARN, "radudpget: length too small");
523             continue;
524         }
525
526         if (cnt < len) {
527             debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
528             continue;
529         }
530         if (cnt > len)
531             debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
532
533         if (client)
534             if (*client)
535                 p = find_conf('U', (struct sockaddr *)&from, NULL, (*client)->conf);
536             else
537                 p = find_conf('U', (struct sockaddr *)&from, clconfs, NULL);
538         else
539             if (*server)
540                 p = find_conf('U', (struct sockaddr *)&from, NULL, (*server)->conf);
541             else
542                 p = find_conf('U', (struct sockaddr *)&from, srvconfs, NULL);
543
544         if (!p) {
545             debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer, ignoring");
546             continue;
547         }
548         
549         rad = malloc(len);
550         if (!rad) {
551             debug(DBG_ERR, "radudpget: malloc failed");
552             continue;
553         }
554         
555         if (client && !*client) {
556             node = list_first(p->clients);
557             *client = node ? (struct client *)node->data : addclient(p);
558             if (!*client) {
559                 free(rad);
560                 continue;
561             }
562         } else if (server && !*server)
563             *server = p->servers;
564         
565         break;
566     }
567     memcpy(rad, buf, len);
568     if (sa)
569         *sa = from;
570     return rad;
571 }
572
573 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
574     int loc, i, l, n, r = 0;
575     char *v;
576     X509_EXTENSION *ex;
577     STACK_OF(GENERAL_NAME) *alt;
578     GENERAL_NAME *gn;
579     
580     debug(DBG_DBG, "subjectaltnameaddr");
581     
582     loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
583     if (loc < 0)
584         return r;
585     
586     ex = X509_get_ext(cert, loc);
587     alt = X509V3_EXT_d2i(ex);
588     if (!alt)
589         return r;
590     
591     n = sk_GENERAL_NAME_num(alt);
592     for (i = 0; i < n; i++) {
593         gn = sk_GENERAL_NAME_value(alt, i);
594         if (gn->type != GEN_IPADD)
595             continue;
596         r = -1;
597         v = (char *)ASN1_STRING_data(gn->d.ia5);
598         l = ASN1_STRING_length(gn->d.ia5);
599         if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
600             && !memcmp(v, &addr, l)) {
601             r = 1;
602             break;
603         }
604     }
605     GENERAL_NAMES_free(alt);
606     return r;
607 }
608
609 int subjectaltnameregexp(X509 *cert, int type, char *exact,  regex_t *regex) {
610     int loc, i, l, n, r = 0;
611     char *s, *v;
612     X509_EXTENSION *ex;
613     STACK_OF(GENERAL_NAME) *alt;
614     GENERAL_NAME *gn;
615     
616     debug(DBG_DBG, "subjectaltnameregexp");
617     
618     loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
619     if (loc < 0)
620         return r;
621     
622     ex = X509_get_ext(cert, loc);
623     alt = X509V3_EXT_d2i(ex);
624     if (!alt)
625         return r;
626     
627     n = sk_GENERAL_NAME_num(alt);
628     for (i = 0; i < n; i++) {
629         gn = sk_GENERAL_NAME_value(alt, i);
630         if (gn->type != type)
631             continue;
632         r = -1;
633         v = (char *)ASN1_STRING_data(gn->d.ia5);
634         l = ASN1_STRING_length(gn->d.ia5);
635         if (l <= 0)
636             continue;
637 #ifdef DEBUG
638         printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
639 #endif  
640         if (exact) {
641             if (memcmp(v, exact, l))
642                 continue;
643         } else {
644             s = stringcopy((char *)v, l);
645             if (!s) {
646                 debug(DBG_ERR, "malloc failed");
647                 continue;
648             }
649             if (regexec(regex, s, 0, NULL, 0)) {
650                 free(s);
651                 continue;
652             }
653             free(s);
654         }
655         r = 1;
656         break;
657     }
658     GENERAL_NAMES_free(alt);
659     return r;
660 }
661
662 int tlsverifycert(SSL *ssl, struct clsrvconf *conf) {
663     int l, loc, r;
664     X509 *cert;
665     X509_NAME *nm;
666     X509_NAME_ENTRY *e;
667     ASN1_STRING *s;
668     char *v;
669     uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
670     unsigned long error;
671     struct in6_addr addr;
672     
673     if (SSL_get_verify_result(ssl) != X509_V_OK) {
674         debug(DBG_ERR, "tlsverifycert: basic validation failed");
675         while ((error = ERR_get_error()))
676             debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
677         return 0;
678     }
679
680     cert = SSL_get_peer_certificate(ssl);
681     if (!cert) {
682         debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
683         return 0;
684     }
685
686     if (conf->prefixlen == 255) {
687         if (inet_pton(AF_INET, conf->host, &addr))
688             type = AF_INET;
689         else if (inet_pton(AF_INET6, conf->host, &addr))
690             type = AF_INET6;
691
692         r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
693         if (r) {
694             if (r < 0) {
695                 X509_free(cert);
696                 debug(DBG_DBG, "tlsverifycert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
697                 return 0;
698             }
699             debug(DBG_DBG, "tlsverifycert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
700         } else {
701             nm = X509_get_subject_name(cert);
702             loc = -1;
703             for (;;) {
704                 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
705                 if (loc == -1)
706                     break;
707                 e = X509_NAME_get_entry(nm, loc);
708                 s = X509_NAME_ENTRY_get_data(e);
709                 v = (char *) ASN1_STRING_data(s);
710                 l = ASN1_STRING_length(s);
711                 if (l < 0)
712                     continue;
713 #ifdef DEBUG
714                 printfchars(NULL, "cn", NULL, v, l);
715 #endif      
716                 if (l == strlen(conf->host) && !strncasecmp(conf->host, v, l)) {
717                     r = 1;
718                     debug(DBG_DBG, "tlsverifycert: Found cn matching host %s", conf->host);
719                     break;
720                 }
721             }
722             if (!r) {
723                 X509_free(cert);
724                 debug(DBG_ERR, "tlsverifycert: cn not matching host %s", conf->host);
725                 return 0;
726             }
727         }
728     }
729     if (conf->certuriregex) {
730         r = subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex);
731         if (r < 1) {
732             debug(DBG_DBG, "tlsverifycert: subjectaltname URI not matching regex");
733             X509_free(cert);
734             return 0;
735         }
736         debug(DBG_DBG, "tlsverifycert: subjectaltname URI matching regex");
737     }
738     X509_free(cert);
739     return 1;
740 }
741
742 void tlsconnect(struct server *server, struct timeval *when, char *text) {
743     struct timeval now;
744     time_t elapsed;
745
746     debug(DBG_DBG, "tlsconnect called from %s", text);
747     pthread_mutex_lock(&server->lock);
748     if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
749         /* already reconnected, nothing to do */
750         debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
751         pthread_mutex_unlock(&server->lock);
752         return;
753     }
754
755     debug(DBG_DBG, "tlsconnect %s", text);
756
757     for (;;) {
758         gettimeofday(&now, NULL);
759         elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
760         if (server->connectionok) {
761             server->connectionok = 0;
762             sleep(10);
763         } else if (elapsed < 5)
764             sleep(10);
765         else if (elapsed < 300) {
766             debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
767             sleep(elapsed);
768         } else if (elapsed < 100000) {
769             debug(DBG_INFO, "tlsconnect: sleeping %ds", 600);
770             sleep(600);
771         } else
772             server->lastconnecttry.tv_sec = now.tv_sec;  /* no sleep at startup */
773         debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
774         if (server->sock >= 0)
775             close(server->sock);
776         if ((server->sock = connecttcp(server->conf->addrinfo)) < 0) {
777             debug(DBG_ERR, "tlsconnect: connecttcp failed");
778             continue;
779         }
780         
781         SSL_free(server->ssl);
782         server->ssl = SSL_new(server->conf->ssl_ctx);
783         SSL_set_fd(server->ssl, server->sock);
784         if (SSL_connect(server->ssl) > 0 && tlsverifycert(server->ssl, server->conf))
785             break;
786     }
787     debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
788     gettimeofday(&server->lastconnecttry, NULL);
789     pthread_mutex_unlock(&server->lock);
790 }
791
792 unsigned char *radtlsget(SSL *ssl) {
793     int cnt, total, len;
794     unsigned char buf[4], *rad;
795
796     for (;;) {
797         for (total = 0; total < 4; total += cnt) {
798             cnt = SSL_read(ssl, buf + total, 4 - total);
799             if (cnt <= 0) {
800                 debug(DBG_ERR, "radtlsget: connection lost");
801                 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
802                     /* remote end sent close_notify, send one back */
803                     SSL_shutdown(ssl);
804                 }
805                 return NULL;
806             }
807         }
808
809         len = RADLEN(buf);
810         rad = malloc(len);
811         if (!rad) {
812             debug(DBG_ERR, "radtlsget: malloc failed");
813             continue;
814         }
815         memcpy(rad, buf, 4);
816
817         for (; total < len; total += cnt) {
818             cnt = SSL_read(ssl, rad + total, len - total);
819             if (cnt <= 0) {
820                 debug(DBG_ERR, "radtlsget: connection lost");
821                 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
822                     /* remote end sent close_notify, send one back */
823                     SSL_shutdown(ssl);
824                 }
825                 free(rad);
826                 return NULL;
827             }
828         }
829     
830         if (total >= 20)
831             break;
832         
833         free(rad);
834         debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
835     }
836     
837     debug(DBG_DBG, "radtlsget: got %d bytes", total);
838     return rad;
839 }
840
841 int clientradput(struct server *server, unsigned char *rad) {
842     int cnt;
843     size_t len;
844     unsigned long error;
845     struct timeval lastconnecttry;
846     struct clsrvconf *conf = server->conf;
847     
848     len = RADLEN(rad);
849     if (conf->type == 'U') {
850         if (sendto(server->sock, rad, len, 0, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen) >= 0) {
851             debug(DBG_DBG, "clienradput: sent UDP of length %d to %s port %s", len, conf->host, conf->port);
852             return 1;
853         }
854         debug(DBG_WARN, "clientradput: send failed");
855         return 0;
856     }
857
858     lastconnecttry = server->lastconnecttry;
859     while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
860         while ((error = ERR_get_error()))
861             debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
862         tlsconnect(server, &lastconnecttry, "clientradput");
863         lastconnecttry = server->lastconnecttry;
864     }
865
866     server->connectionok = 1;
867     debug(DBG_DBG, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
868     return 1;
869 }
870
871 int radsign(unsigned char *rad, unsigned char *sec) {
872     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
873     static unsigned char first = 1;
874     static EVP_MD_CTX mdctx;
875     unsigned int md_len;
876     int result;
877     
878     pthread_mutex_lock(&lock);
879     if (first) {
880         EVP_MD_CTX_init(&mdctx);
881         first = 0;
882     }
883
884     result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
885         EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
886         EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
887         EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
888         md_len == 16);
889     pthread_mutex_unlock(&lock);
890     return result;
891 }
892
893 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
894     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
895     static unsigned char first = 1;
896     static EVP_MD_CTX mdctx;
897     unsigned char hash[EVP_MAX_MD_SIZE];
898     unsigned int len;
899     int result;
900     
901     pthread_mutex_lock(&lock);
902     if (first) {
903         EVP_MD_CTX_init(&mdctx);
904         first = 0;
905     }
906
907     len = RADLEN(rad);
908     
909     result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
910               EVP_DigestUpdate(&mdctx, rad, 4) &&
911               EVP_DigestUpdate(&mdctx, reqauth, 16) &&
912               (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
913               EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
914               EVP_DigestFinal_ex(&mdctx, hash, &len) &&
915               len == 16 &&
916               !memcmp(hash, rad + 4, 16));
917     pthread_mutex_unlock(&lock);
918     return result;
919 }
920               
921 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
922     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
923     static unsigned char first = 1;
924     static HMAC_CTX hmacctx;
925     unsigned int md_len;
926     uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
927     
928     pthread_mutex_lock(&lock);
929     if (first) {
930         HMAC_CTX_init(&hmacctx);
931         first = 0;
932     }
933
934     memcpy(auth, authattr, 16);
935     memset(authattr, 0, 16);
936     md_len = 0;
937     HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
938     HMAC_Update(&hmacctx, rad, RADLEN(rad));
939     HMAC_Final(&hmacctx, hash, &md_len);
940     memcpy(authattr, auth, 16);
941     if (md_len != 16) {
942         debug(DBG_WARN, "message auth computation failed");
943         pthread_mutex_unlock(&lock);
944         return 0;
945     }
946
947     if (memcmp(auth, hash, 16)) {
948         debug(DBG_WARN, "message authenticator, wrong value");
949         pthread_mutex_unlock(&lock);
950         return 0;
951     }   
952         
953     pthread_mutex_unlock(&lock);
954     return 1;
955 }
956
957 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
958     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
959     static unsigned char first = 1;
960     static HMAC_CTX hmacctx;
961     unsigned int md_len;
962
963     if (!authattrval)
964         return 1;
965     
966     pthread_mutex_lock(&lock);
967     if (first) {
968         HMAC_CTX_init(&hmacctx);
969         first = 0;
970     }
971
972     memset(authattrval, 0, 16);
973     md_len = 0;
974     HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
975     HMAC_Update(&hmacctx, rad, RADLEN(rad));
976     HMAC_Final(&hmacctx, authattrval, &md_len);
977     if (md_len != 16) {
978         debug(DBG_WARN, "message auth computation failed");
979         pthread_mutex_unlock(&lock);
980         return 0;
981     }
982
983     pthread_mutex_unlock(&lock);
984     return 1;
985 }
986
987 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
988     while (length > 1) {
989         if (ATTRTYPE(attrs) == type)
990             return attrs;
991         length -= ATTRLEN(attrs);
992         attrs += ATTRLEN(attrs);
993     }
994     return NULL;
995 }
996
997 void freerqdata(struct request *rq) {
998     if (rq->origusername)
999         free(rq->origusername);
1000     if (rq->buf)
1001         free(rq->buf);
1002 }
1003
1004 void sendrq(struct server *to, struct request *rq) {
1005     int i;
1006     uint8_t *attr;
1007
1008     pthread_mutex_lock(&to->newrq_mutex);
1009     /* might simplify if only try nextid, might be ok */
1010     for (i = to->nextid; i < MAX_REQUESTS; i++)
1011         if (!to->requests[i].buf)
1012             break;
1013     if (i == MAX_REQUESTS) {
1014         for (i = 0; i < to->nextid; i++)
1015             if (!to->requests[i].buf)
1016                 break;
1017         if (i == to->nextid) {
1018             debug(DBG_WARN, "No room in queue, dropping request");
1019             freerqdata(rq);
1020             pthread_mutex_unlock(&to->newrq_mutex);
1021             return;
1022         }
1023     }
1024     
1025     rq->buf[1] = (char)i;
1026
1027     attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1028     if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1029         freerqdata(rq);
1030         pthread_mutex_unlock(&to->newrq_mutex);
1031         return;
1032     }
1033
1034     debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1035     to->requests[i] = *rq;
1036     to->nextid = i + 1;
1037
1038     if (!to->newrq) {
1039         to->newrq = 1;
1040         debug(DBG_DBG, "signalling client writer");
1041         pthread_cond_signal(&to->newrq_cond);
1042     }
1043     pthread_mutex_unlock(&to->newrq_mutex);
1044 }
1045
1046 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
1047     struct reply *reply;
1048     uint8_t first;
1049     
1050     if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1051         free(buf);
1052         debug(DBG_WARN, "sendreply: failed to sign message");
1053         return;
1054     }
1055
1056     reply = malloc(sizeof(struct reply));
1057     if (!reply) {
1058         free(buf);
1059         debug(DBG_ERR, "sendreply: malloc failed");
1060         return;
1061     }
1062     memset(reply, 0, sizeof(struct reply));
1063     reply->buf = buf;
1064     if (tosa)
1065         reply->tosa = *tosa;
1066     
1067     pthread_mutex_lock(&to->replyq->mutex);
1068
1069     first = list_first(to->replyq->replies) == NULL;
1070     
1071     if (!list_push(to->replyq->replies, reply)) {
1072         pthread_mutex_unlock(&to->replyq->mutex);
1073         free(reply);
1074         free(buf);
1075         debug(DBG_ERR, "sendreply: malloc failed");
1076         return;
1077     }
1078     
1079     if (first) {
1080         debug(DBG_DBG, "signalling server writer");
1081         pthread_cond_signal(&to->replyq->cond);
1082     }
1083     pthread_mutex_unlock(&to->replyq->mutex);
1084 }
1085
1086 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1087     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1088     static unsigned char first = 1;
1089     static EVP_MD_CTX mdctx;
1090     unsigned char hash[EVP_MAX_MD_SIZE], *input;
1091     unsigned int md_len;
1092     uint8_t i, offset = 0, out[128];
1093     
1094     pthread_mutex_lock(&lock);
1095     if (first) {
1096         EVP_MD_CTX_init(&mdctx);
1097         first = 0;
1098     }
1099
1100     input = auth;
1101     for (;;) {
1102         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1103             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1104             !EVP_DigestUpdate(&mdctx, input, 16) ||
1105             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1106             md_len != 16) {
1107             pthread_mutex_unlock(&lock);
1108             return 0;
1109         }
1110         for (i = 0; i < 16; i++)
1111             out[offset + i] = hash[i] ^ in[offset + i];
1112         input = out + offset - 16;
1113         offset += 16;
1114         if (offset == len)
1115             break;
1116     }
1117     memcpy(in, out, len);
1118     pthread_mutex_unlock(&lock);
1119     return 1;
1120 }
1121
1122 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1123     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1124     static unsigned char first = 1;
1125     static EVP_MD_CTX mdctx;
1126     unsigned char hash[EVP_MAX_MD_SIZE], *input;
1127     unsigned int md_len;
1128     uint8_t i, offset = 0, out[128];
1129     
1130     pthread_mutex_lock(&lock);
1131     if (first) {
1132         EVP_MD_CTX_init(&mdctx);
1133         first = 0;
1134     }
1135
1136     input = auth;
1137     for (;;) {
1138         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1139             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1140             !EVP_DigestUpdate(&mdctx, input, 16) ||
1141             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1142             md_len != 16) {
1143             pthread_mutex_unlock(&lock);
1144             return 0;
1145         }
1146         for (i = 0; i < 16; i++)
1147             out[offset + i] = hash[i] ^ in[offset + i];
1148         input = in + offset;
1149         offset += 16;
1150         if (offset == len)
1151             break;
1152     }
1153     memcpy(in, out, len);
1154     pthread_mutex_unlock(&lock);
1155     return 1;
1156 }
1157
1158 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1159     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1160     static unsigned char first = 1;
1161     static EVP_MD_CTX mdctx;
1162     unsigned char hash[EVP_MAX_MD_SIZE];
1163     unsigned int md_len;
1164     uint8_t i, offset;
1165     
1166     pthread_mutex_lock(&lock);
1167     if (first) {
1168         EVP_MD_CTX_init(&mdctx);
1169         first = 0;
1170     }
1171
1172 #if 0
1173     printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1174     printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1175     printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1176 #endif
1177     
1178     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1179         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1180         !EVP_DigestUpdate(&mdctx, auth, 16) ||
1181         !EVP_DigestUpdate(&mdctx, salt, 2) ||
1182         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1183         pthread_mutex_unlock(&lock);
1184         return 0;
1185     }
1186
1187 #if 0    
1188     printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1189 #endif
1190     
1191     for (i = 0; i < 16; i++)
1192         text[i] ^= hash[i];
1193     
1194     for (offset = 16; offset < len; offset += 16) {
1195 #if 0   
1196         printf("text + offset - 16 c(%d): ", offset / 16);
1197         printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1198 #endif
1199         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1200             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1201             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1202             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1203             md_len != 16) {
1204             pthread_mutex_unlock(&lock);
1205             return 0;
1206         }
1207 #if 0
1208         printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1209 #endif    
1210         
1211         for (i = 0; i < 16; i++)
1212             text[offset + i] ^= hash[i];
1213     }
1214     
1215 #if 0
1216     printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1217 #endif
1218
1219     pthread_mutex_unlock(&lock);
1220     return 1;
1221 }
1222
1223 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1224     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1225     static unsigned char first = 1;
1226     static EVP_MD_CTX mdctx;
1227     unsigned char hash[EVP_MAX_MD_SIZE];
1228     unsigned int md_len;
1229     uint8_t i, offset;
1230     char plain[255];
1231     
1232     pthread_mutex_lock(&lock);
1233     if (first) {
1234         EVP_MD_CTX_init(&mdctx);
1235         first = 0;
1236     }
1237
1238 #if 0
1239     printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1240     printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1241     printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1242 #endif
1243     
1244     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1245         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1246         !EVP_DigestUpdate(&mdctx, auth, 16) ||
1247         !EVP_DigestUpdate(&mdctx, salt, 2) ||
1248         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1249         pthread_mutex_unlock(&lock);
1250         return 0;
1251     }
1252
1253 #if 0    
1254     printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1255 #endif
1256     
1257     for (i = 0; i < 16; i++)
1258         plain[i] = text[i] ^ hash[i];
1259     
1260     for (offset = 16; offset < len; offset += 16) {
1261 #if 0   
1262         printf("text + offset - 16 c(%d): ", offset / 16);
1263         printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1264 #endif
1265         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1266             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1267             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1268             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1269             md_len != 16) {
1270             pthread_mutex_unlock(&lock);
1271             return 0;
1272         }
1273 #if 0
1274         printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1275 #endif    
1276
1277         for (i = 0; i < 16; i++)
1278             plain[offset + i] = text[offset + i] ^ hash[i];
1279     }
1280
1281     memcpy(text, plain, len);
1282 #if 0
1283     printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1284 #endif
1285
1286     pthread_mutex_unlock(&lock);
1287     return 1;
1288 }
1289
1290 struct realm *id2realm(char *id, uint8_t len) {
1291     struct list_node *entry;
1292     struct realm *realm;
1293     
1294     for (entry = list_first(realms); entry; entry = list_next(entry)) {
1295         realm = (struct realm *)entry->data;
1296         if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1297             debug(DBG_DBG, "found matching realm: %s", realm->name);
1298             return realm;
1299         }
1300     }
1301     return NULL;
1302 }
1303
1304 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
1305     int i;
1306     
1307     pthread_mutex_lock(&to->newrq_mutex);
1308     for (i = 0; i < MAX_REQUESTS; i++)
1309         if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
1310             break;
1311     pthread_mutex_unlock(&to->newrq_mutex);
1312     
1313     return i < MAX_REQUESTS;
1314 }
1315
1316 int attrvalidate(unsigned char *attrs, int length) {
1317     while (length > 1) {
1318         if (ATTRLEN(attrs) < 2) {
1319             debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1320             return 0;
1321         }
1322         length -= ATTRLEN(attrs);
1323         if (length < 0) {
1324             debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1325             return 0;
1326         }
1327         attrs += ATTRLEN(attrs);
1328     }
1329     if (length)
1330         debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1331     return 1;
1332 }
1333
1334 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1335     if (len < 16 || len > 128 || len % 16) {
1336         debug(DBG_WARN, "pwdrecrypt: invalid password length");
1337         return 0;
1338     }
1339         
1340     if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1341         debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1342         return 0;
1343     }
1344 #ifdef DEBUG
1345     printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1346 #endif  
1347     if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1348         debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1349         return 0;
1350     }
1351     return 1;
1352 }
1353
1354 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1355     if (len < 18)
1356         return 0;
1357     if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1358         debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1359         return 0;
1360     }
1361     if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1362         debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1363         return 0;
1364     }
1365     return 1;
1366 }
1367
1368 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1369            char *oldsecret, char *newsecret) {
1370     unsigned char *attr;
1371     
1372     for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1373         debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1374         if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1375             return 0;
1376     }
1377     return 1;
1378 }
1379
1380 /* returns a pointer to the resized attribute value */
1381 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1382     uint8_t *attrs, *attr, vallen;
1383     uint16_t len;
1384     unsigned char *new;
1385     
1386     len = RADLEN(*buf) - 20;
1387     attrs = *buf + 20;
1388
1389     attr = attrget(attrs, len, type);
1390     if (!attr)
1391         return NULL;
1392     
1393     vallen = ATTRVALLEN(attr);
1394     if (vallen == newvallen)
1395         return attr + 2;
1396
1397     len += newvallen - vallen;
1398     if (newvallen > vallen) {
1399         new = realloc(*buf, len);
1400         if (!new) {
1401             debug(DBG_ERR, "resizeattr: malloc failed");
1402             return NULL;
1403         }
1404         if (new != *buf) {
1405             attr += new - *buf;
1406             attrs = new + 20;
1407             *buf = new;
1408         }
1409     }
1410     memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1411     attr[1] = newvallen + 2;
1412     ((uint16_t *)*buf)[1] = htons(len + 20);
1413     return attr + 2;
1414 }
1415                 
1416 int rewriteusername(struct request *rq, char *in) {
1417     size_t nmatch = 10, reslen = 0, start = 0;
1418     regmatch_t pmatch[10], *pfield;
1419     int i;
1420     unsigned char *result;
1421     char *out = rq->from->conf->rewriteattrreplacement;
1422     
1423     if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1424         debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1425         return 1;
1426     }
1427     
1428     rq->origusername = stringcopy(in, 0);
1429     if (!rq->origusername)
1430         return 0;
1431     
1432     for (i = start; out[i]; i++) {
1433         if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1434             pfield = &pmatch[out[i + 1] - '0'];
1435             if (pfield->rm_so >= 0) {
1436                 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1437                 start = i + 2;
1438             }
1439             i++;
1440         }
1441     }
1442     reslen += i - start;
1443
1444     result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1445     if (!result)
1446         return 0;
1447     
1448     start = 0;
1449     reslen = 0;
1450     for (i = start; out[i]; i++) {
1451         if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1452             pfield = &pmatch[out[i + 1] - '0'];
1453             if (pfield->rm_so >= 0) {
1454                 memcpy(result + reslen, out + start, i - start);
1455                 reslen += i - start;
1456                 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1457                 reslen += pfield->rm_eo - pfield->rm_so;
1458                 start = i + 2;
1459             }
1460             i++;
1461         }
1462     }
1463
1464     memcpy(result + reslen, out + start, i - start);
1465     reslen += i - start;
1466     memcpy(in, result, reslen);
1467     in[reslen] = '\0';
1468     return 1;
1469 }
1470
1471 void acclog(unsigned char *attrs, int length, char *host) {
1472     unsigned char *attr;
1473     char username[256];
1474     
1475     attr = attrget(attrs, length, RAD_Attr_User_Name);
1476     if (!attr) {
1477         debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1478         return;
1479     }
1480     memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1481     username[ATTRVALLEN(attr)] = '\0';
1482     debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1483 }
1484         
1485 void respondaccounting(struct request *rq) {
1486     unsigned char *resp;
1487
1488     resp = malloc(20);
1489     if (!resp) {
1490         debug(DBG_ERR, "respondstatusserver: malloc failed");
1491         return;
1492     }
1493     memcpy(resp, rq->buf, 20);
1494     resp[0] = RAD_Accounting_Response;
1495     resp[2] = 0;
1496     resp[3] = 20;
1497     debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1498     sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1499 }
1500
1501 void respondstatusserver(struct request *rq) {
1502     unsigned char *resp;
1503
1504     resp = malloc(20);
1505     if (!resp) {
1506         debug(DBG_ERR, "respondstatusserver: malloc failed");
1507         return;
1508     }
1509     memcpy(resp, rq->buf, 20);
1510     resp[0] = RAD_Access_Accept;
1511     resp[2] = 0;
1512     resp[3] = 20;
1513     debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1514     sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1515 }
1516
1517 void respondreject(struct request *rq, char *message) {
1518     unsigned char *resp;
1519     int len = 20;
1520
1521     if (message && *message)
1522         len += 2 + strlen(message);
1523     
1524     resp = malloc(len);
1525     if (!resp) {
1526         debug(DBG_ERR, "respondreject: malloc failed");
1527         return;
1528     }
1529     memcpy(resp, rq->buf, 20);
1530     resp[0] = RAD_Access_Reject;
1531     *(uint16_t *)(resp + 2) = htons(len);
1532     if (message && *message) {
1533         resp[20] = RAD_Attr_Reply_Message;
1534         resp[21] = len - 20;
1535         memcpy(resp + 22, message, len - 22);
1536     }
1537     sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1538 }
1539
1540 struct server *realm2server(struct realm *realm) {
1541     struct list_node *entry;
1542     struct server *server, *best = NULL;
1543     
1544     for (entry = list_first(realm->srvconfs); entry; entry = list_next(entry)) {
1545         server = ((struct clsrvconf *)entry->data)->servers;
1546         if (!server->connectionok)
1547             continue;
1548         if (!server->loststatsrv)
1549             return server;
1550         if (!best) {
1551             best = server;
1552             continue;
1553         }
1554         if (server->loststatsrv < best->loststatsrv)
1555             best = server;
1556     }
1557     return best;
1558 }
1559
1560 void radsrv(struct request *rq) {
1561     uint8_t code, id, *auth, *attrs, *attr;
1562     uint16_t len;
1563     struct server *to = NULL;
1564     char username[256];
1565     unsigned char newauth[16];
1566     struct realm *realm = NULL;
1567     
1568     code = *(uint8_t *)rq->buf;
1569     id = *(uint8_t *)(rq->buf + 1);
1570     len = RADLEN(rq->buf);
1571     auth = (uint8_t *)(rq->buf + 4);
1572
1573     debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1574     
1575     if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1576         debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1577         freerqdata(rq);
1578         return;
1579     }
1580
1581     len -= 20;
1582     attrs = rq->buf + 20;
1583
1584     if (!attrvalidate(attrs, len)) {
1585         debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1586         freerqdata(rq);
1587         return;
1588     }
1589
1590     attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1591     if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
1592         debug(DBG_WARN, "radsrv: message authentication failed");
1593         freerqdata(rq);
1594         return;
1595     }
1596
1597     if (code != RAD_Access_Request) {
1598         switch (code) {
1599         case RAD_Accounting_Request:
1600             acclog(attrs, len, rq->from->conf->host);
1601             respondaccounting(rq);
1602             break;
1603         case RAD_Status_Server:
1604             respondstatusserver(rq);
1605             break;
1606         }
1607         freerqdata(rq);
1608         return;
1609     }
1610
1611     /* code == RAD_Access_Request */
1612     attr = attrget(attrs, len, RAD_Attr_User_Name);
1613     if (!attr) {
1614         debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1615         freerqdata(rq);
1616         return;
1617     }
1618     memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1619     username[ATTRVALLEN(attr)] = '\0';
1620
1621     if (rq->from->conf->rewriteattrregex) {
1622         if (!rewriteusername(rq, username)) {
1623             debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1624             freerqdata(rq);
1625             return;
1626         }
1627         len = RADLEN(rq->buf) - 20;
1628         auth = (uint8_t *)(rq->buf + 4);
1629         attrs = rq->buf + 20;
1630     }
1631
1632     if (rq->origusername)
1633         debug(DBG_DBG, "Access Request with username: %s (originally %s)", username, rq->origusername);
1634     else
1635         debug(DBG_DBG, "Access Request with username: %s", username);
1636         
1637     realm = id2realm(username, strlen(username));
1638     if (!realm) {
1639         debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1640         freerqdata(rq);
1641         return;
1642     }
1643         
1644     to = realm2server(realm);
1645     if (to && rqinqueue(to, rq->from, id)) {
1646         debug(DBG_INFO, "radsrv: already got request from host %s with id %d, ignoring", rq->from->conf->host, id);
1647         freerqdata(rq);
1648         return;
1649     }
1650
1651     if (!to) {
1652         if (realm->message) {
1653             debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, username);
1654             respondreject(rq, realm->message);
1655         }
1656         freerqdata(rq);
1657         return;
1658     }
1659     
1660     if (!RAND_bytes(newauth, 16)) {
1661         debug(DBG_WARN, "radsrv: failed to generate random auth");
1662         freerqdata(rq);
1663         return;
1664     }
1665
1666 #ifdef DEBUG
1667     printfchars(NULL, "auth", "%02x ", auth, 16);
1668 #endif
1669
1670     attr = attrget(attrs, len, RAD_Attr_User_Password);
1671     if (attr) {
1672         debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1673         if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1674             freerqdata(rq);
1675             return;
1676         }
1677     }
1678     
1679     attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1680     if (attr) {
1681         debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1682         if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1683             freerqdata(rq);
1684             return;
1685         }
1686     }
1687
1688     rq->origid = id;
1689     memcpy(rq->origauth, auth, 16);
1690     memcpy(auth, newauth, 16);
1691     sendrq(to, rq);
1692 }
1693
1694 int replyh(struct server *server, unsigned char *buf) {
1695     struct client *from;
1696     struct request *rq;
1697     int i, len, sublen;
1698     unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
1699     struct sockaddr_storage fromsa;
1700     char tmp[256];
1701     
1702     server->connectionok = 1;
1703     server->loststatsrv = 0;
1704         
1705     i = buf[1]; /* i is the id */
1706
1707     switch (*buf) {
1708     case RAD_Access_Accept:
1709         debug(DBG_DBG, "got Access Accept with id %d", i);
1710         break;
1711     case RAD_Access_Reject:
1712         debug(DBG_DBG, "got Access Reject with id %d", i);
1713         break;
1714     case RAD_Access_Challenge:
1715         debug(DBG_DBG, "got Access Challenge with id %d", i);
1716         break;
1717     default:
1718         debug(DBG_INFO, "replyh: discarding, only accept access accept, access reject and access challenge messages");
1719         return 0;
1720     }
1721
1722     rq = server->requests + i;
1723         
1724     pthread_mutex_lock(&server->newrq_mutex);
1725     if (!rq->buf || !rq->tries) {
1726         pthread_mutex_unlock(&server->newrq_mutex);
1727         debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
1728         return 0;
1729     }
1730
1731     if (rq->received) {
1732         pthread_mutex_unlock(&server->newrq_mutex);
1733         debug(DBG_INFO, "replyh: already received, ignoring reply");
1734         return 0;
1735     }
1736         
1737     if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
1738         pthread_mutex_unlock(&server->newrq_mutex);
1739         debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
1740         return 0;
1741     }
1742         
1743     from = rq->from;
1744     len = RADLEN(buf) - 20;
1745     attrs = buf + 20;
1746
1747     if (!attrvalidate(attrs, len)) {
1748         pthread_mutex_unlock(&server->newrq_mutex);
1749         debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
1750         return 0;
1751     }
1752         
1753     /* Message Authenticator */
1754     messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1755     if (messageauth) {
1756         if (ATTRVALLEN(messageauth) != 16) {
1757             pthread_mutex_unlock(&server->newrq_mutex);
1758             debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
1759             return 0;
1760         }
1761         memcpy(tmp, buf + 4, 16);
1762         memcpy(buf + 4, rq->buf + 4, 16);
1763         if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
1764             pthread_mutex_unlock(&server->newrq_mutex);
1765             debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
1766             return 0;
1767         }
1768         memcpy(buf + 4, tmp, 16);
1769         debug(DBG_DBG, "replyh: message auth ok");
1770     }
1771         
1772     if (*rq->buf == RAD_Status_Server) {
1773         rq->received = 1;
1774         pthread_mutex_unlock(&server->newrq_mutex);
1775         debug(DBG_INFO, "replyh: got status server response from %s", server->conf->host);
1776         return 0;
1777     }
1778
1779     /* MS MPPE */
1780     for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1781         if (ATTRVALLEN(attr) <= 4)
1782             break;
1783             
1784         if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55)  /* 311 == MS */
1785             continue;
1786             
1787         sublen = ATTRVALLEN(attr) - 4;
1788         subattrs = ATTRVAL(attr) + 4;  
1789         if (!attrvalidate(subattrs, sublen) ||
1790             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1791                     rq, server->conf->secret, from->conf->secret) ||
1792             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1793                     rq, server->conf->secret, from->conf->secret))
1794             break;
1795     }
1796     if (attr) {
1797         pthread_mutex_unlock(&server->newrq_mutex);
1798         debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1799         return 0;
1800     }
1801         
1802     if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject) {
1803         attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
1804         /* we know the attribute exists */
1805         memcpy(tmp, ATTRVAL(attr), ATTRVALLEN(attr));
1806         tmp[ATTRVALLEN(attr)] = '\0';
1807         switch (*buf) {
1808         case RAD_Access_Accept:
1809             if (rq->origusername)
1810                 debug(DBG_INFO, "Access Accept for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1811             else
1812                 debug(DBG_INFO, "Access Accept for %s from %s", tmp, server->conf->host);
1813             break;
1814         case RAD_Access_Reject:
1815             if (rq->origusername)
1816                 debug(DBG_INFO, "Access Reject for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1817             else
1818                 debug(DBG_INFO, "Access Reject for %s from %s", tmp, server->conf->host);
1819             break;
1820         }
1821     }
1822         
1823     buf[1] = (char)rq->origid;
1824     memcpy(buf + 4, rq->origauth, 16);
1825 #ifdef DEBUG    
1826     printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1827 #endif
1828
1829     if (rq->origusername) {
1830         username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
1831         if (!username) {
1832             pthread_mutex_unlock(&server->newrq_mutex);
1833             debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1834             return 0;
1835         }
1836         memcpy(username, rq->origusername, strlen(rq->origusername));
1837         len = RADLEN(buf) - 20;
1838         attrs = buf + 20;
1839         if (messageauth)
1840             messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1841     }
1842         
1843     if (messageauth) {
1844         if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
1845             pthread_mutex_unlock(&server->newrq_mutex);
1846             debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
1847             return 0;
1848         }
1849         debug(DBG_DBG, "replyh: computed messageauthattr");
1850     }
1851
1852     if (from->conf->type == 'U')
1853         fromsa = rq->fromsa;
1854     /* once we set received = 1, rq may be reused */
1855     rq->received = 1;
1856     pthread_mutex_unlock(&server->newrq_mutex);
1857
1858     debug(DBG_DBG, "replyh: giving packet back to where it came from");
1859     sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
1860     return 1;
1861 }
1862
1863 void *udpclientrd(void *arg) {
1864     struct server *server;
1865     unsigned char *buf;
1866     int *s = (int *)arg;
1867     
1868     for (;;) {
1869         server = NULL;
1870         buf = radudpget(*s, NULL, &server, NULL);
1871         if (!replyh(server, buf))
1872             free(buf);
1873     }
1874 }
1875
1876 void *tlsclientrd(void *arg) {
1877     struct server *server = (struct server *)arg;
1878     unsigned char *buf;
1879     struct timeval lastconnecttry;
1880     
1881     for (;;) {
1882         /* yes, lastconnecttry is really necessary */
1883         lastconnecttry = server->lastconnecttry;
1884         buf = radtlsget(server->ssl);
1885         if (!buf) {
1886             tlsconnect(server, &lastconnecttry, "clientrd");
1887             continue;
1888         }
1889
1890         if (!replyh(server, buf))
1891             free(buf);
1892     }
1893 }
1894
1895 void *clientwr(void *arg) {
1896     struct server *server = (struct server *)arg;
1897     struct request *rq;
1898     pthread_t tlsclientrdth;
1899     int i;
1900     uint8_t rnd;
1901     struct timeval now, lastsend;
1902     struct timespec timeout;
1903     struct request statsrvrq;
1904     unsigned char statsrvbuf[38];
1905
1906     memset(&timeout, 0, sizeof(struct timespec));
1907     
1908     if (server->conf->statusserver) {
1909         memset(&statsrvrq, 0, sizeof(struct request));
1910         memset(statsrvbuf, 0, sizeof(statsrvbuf));
1911         statsrvbuf[0] = RAD_Status_Server;
1912         statsrvbuf[3] = 38;
1913         statsrvbuf[20] = RAD_Attr_Message_Authenticator;
1914         statsrvbuf[21] = 18;
1915         gettimeofday(&lastsend, NULL);
1916     }
1917     
1918     if (server->conf->type == 'U') {
1919         server->connectionok = 1;
1920     } else {
1921         tlsconnect(server, NULL, "new client");
1922         server->connectionok = 1;
1923         if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server))
1924             debugx(1, DBG_ERR, "clientwr: pthread_create failed");
1925     }
1926     
1927     for (;;) {
1928         pthread_mutex_lock(&server->newrq_mutex);
1929         if (!server->newrq) {
1930             gettimeofday(&now, NULL);
1931             if (server->conf->statusserver) {
1932                 /* random 0-7 seconds */
1933                 RAND_bytes(&rnd, 1);
1934                 rnd /= 32;
1935                 if (!timeout.tv_sec || timeout.tv_sec - now.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
1936                     timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
1937             }   
1938             if (timeout.tv_sec) {
1939                 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1940                 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1941                 timeout.tv_sec = 0;
1942             } else {
1943                 debug(DBG_DBG, "clientwr: waiting for new request");
1944                 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1945             }
1946         }
1947         if (server->newrq) {
1948             debug(DBG_DBG, "clientwr: got new request");
1949             server->newrq = 0;
1950         } else
1951             debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1952         pthread_mutex_unlock(&server->newrq_mutex);
1953
1954         for (i = 0; i < MAX_REQUESTS; i++) {
1955             pthread_mutex_lock(&server->newrq_mutex);
1956             while (i < MAX_REQUESTS && !server->requests[i].buf)
1957                 i++;
1958             if (i == MAX_REQUESTS) {
1959                 pthread_mutex_unlock(&server->newrq_mutex);
1960                 break;
1961             }
1962             rq = server->requests + i;
1963
1964             if (rq->received) {
1965                 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
1966                 if (rq->buf) {
1967                     debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
1968                     freerqdata(rq);
1969                     /* setting this to NULL means that it can be reused */
1970                     rq->buf = NULL;
1971                 }
1972                 pthread_mutex_unlock(&server->newrq_mutex);
1973                 continue;
1974             }
1975             
1976             gettimeofday(&now, NULL);
1977             if (now.tv_sec < rq->expiry.tv_sec) {
1978                 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1979                     timeout.tv_sec = rq->expiry.tv_sec;
1980                 pthread_mutex_unlock(&server->newrq_mutex);
1981                 continue;
1982             }
1983
1984             if (rq->tries == (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
1985                               ? 1 : REQUEST_RETRIES)) {
1986                 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1987                 if (*rq->buf == RAD_Status_Server) {
1988                     debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->conf->host);
1989                     if (server->loststatsrv < 255)
1990                         server->loststatsrv++;
1991                 }
1992                 freerqdata(rq);
1993                 /* setting this to NULL means that it can be reused */
1994                 rq->buf = NULL;
1995                 pthread_mutex_unlock(&server->newrq_mutex);
1996                 continue;
1997             }
1998             pthread_mutex_unlock(&server->newrq_mutex);
1999
2000             rq->expiry.tv_sec = now.tv_sec +
2001                 (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
2002                  ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
2003             if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2004                 timeout.tv_sec = rq->expiry.tv_sec;
2005             rq->tries++;
2006             clientradput(server, server->requests[i].buf);
2007             gettimeofday(&lastsend, NULL);
2008         }
2009         if (server->conf->statusserver) {
2010             gettimeofday(&now, NULL);
2011             if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
2012                 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2013                     debug(DBG_WARN, "clientwr: failed to generate random auth");
2014                     continue;
2015                 }
2016                 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2017                 if (!statsrvrq.buf) {
2018                     debug(DBG_ERR, "clientwr: malloc failed");
2019                     continue;
2020                 }
2021                 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2022                 debug(DBG_DBG, "clientwr: sending status server to %s", server->conf->host);
2023                 lastsend.tv_sec = now.tv_sec;
2024                 sendrq(server, &statsrvrq);
2025             }
2026         }
2027     }
2028 }
2029
2030 void *udpserverwr(void *arg) {
2031     struct replyq *replyq = udp_server_replyq;
2032     struct reply *reply;
2033     
2034     for (;;) {
2035         pthread_mutex_lock(&replyq->mutex);
2036         while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2037             debug(DBG_DBG, "udp server writer, waiting for signal");
2038             pthread_cond_wait(&replyq->cond, &replyq->mutex);
2039             debug(DBG_DBG, "udp server writer, got signal");
2040         }
2041         pthread_mutex_unlock(&replyq->mutex);
2042
2043         if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
2044                    (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2045             debug(DBG_WARN, "sendudp: send failed");
2046         free(reply->buf);
2047         free(reply);
2048     }
2049 }
2050
2051 void *udpserverrd(void *arg) {
2052     struct request rq;
2053     pthread_t udpserverwrth;
2054     struct clsrvconf *listenres;
2055
2056     listenres = resolve_hostport('U', options.listenudp, DEFAULT_UDP_PORT);
2057     if ((udp_server_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2058         debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2059
2060     debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
2061           listenres->host ? listenres->host : "*", listenres->port);
2062     free(listenres);
2063     
2064     if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
2065         debugx(1, DBG_ERR, "pthread_create failed");
2066     
2067     for (;;) {
2068         memset(&rq, 0, sizeof(struct request));
2069         rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
2070         radsrv(&rq);
2071     }
2072 }
2073
2074 void *udpaccserverrd(void *arg) {
2075     struct request rq;
2076     struct clsrvconf *listenres;
2077     
2078     listenres = resolve_hostport('U', options.listenaccudp, DEFAULT_UDP_PORT);
2079     if ((udp_accserver_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2080         debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2081
2082     debug(DBG_WARN, "udpaccserverrd: listening for UDP on %s:%s",
2083           listenres->host ? listenres->host : "*", listenres->port);
2084     free(listenres);
2085     
2086     for (;;) {
2087         memset(&rq, 0, sizeof(struct request));
2088         rq.buf = radudpget(udp_accserver_sock, &rq.from, NULL, &rq.fromsa);
2089         if (*(uint8_t *)rq.buf == RAD_Accounting_Request) {
2090             radsrv(&rq);
2091             continue;
2092         }
2093         debug(DBG_INFO, "udpaccserverrd: got something other than accounting-request, ignoring");
2094         freerqdata(&rq);
2095     }
2096 }
2097
2098 void *tlsserverwr(void *arg) {
2099     int cnt;
2100     unsigned long error;
2101     struct client *client = (struct client *)arg;
2102     struct replyq *replyq;
2103     struct reply *reply;
2104     
2105     debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
2106     replyq = client->replyq;
2107     for (;;) {
2108         pthread_mutex_lock(&replyq->mutex);
2109         while (!list_first(replyq->replies)) {
2110             if (client->ssl) {      
2111                 debug(DBG_DBG, "tls server writer, waiting for signal");
2112                 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2113                 debug(DBG_DBG, "tls server writer, got signal");
2114             }
2115             if (!client->ssl) {
2116                 /* ssl might have changed while waiting */
2117                 pthread_mutex_unlock(&replyq->mutex);
2118                 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2119                 pthread_exit(NULL);
2120             }
2121         }
2122         reply = (struct reply *)list_shift(replyq->replies);
2123         pthread_mutex_unlock(&replyq->mutex);
2124         cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2125         if (cnt > 0)
2126             debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
2127                   cnt, RADLEN(reply->buf));
2128         else
2129             while ((error = ERR_get_error()))
2130                 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2131         free(reply->buf);
2132         free(reply);
2133     }
2134 }
2135
2136 void *tlsserverrd(void *arg) {
2137     struct request rq;
2138     unsigned long error;
2139     int s;
2140     struct client *client = (struct client *)arg;
2141     pthread_t tlsserverwrth;
2142     SSL *ssl;
2143     
2144     debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2145     ssl = client->ssl;
2146
2147     if (SSL_accept(ssl) <= 0) {
2148         while ((error = ERR_get_error()))
2149             debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2150         debug(DBG_ERR, "SSL_accept failed");
2151         goto errexit;
2152     }
2153     if (tlsverifycert(client->ssl, client->conf)) {
2154         if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2155             debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2156             goto errexit;
2157         }
2158         for (;;) {
2159             memset(&rq, 0, sizeof(struct request));
2160             rq.buf = radtlsget(client->ssl);
2161             if (!rq.buf)
2162                 break;
2163             debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2164             rq.from = client;
2165             radsrv(&rq);
2166         }
2167         debug(DBG_ERR, "tlsserverrd: connection lost");
2168         /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2169         client->ssl = NULL;
2170         pthread_mutex_lock(&client->replyq->mutex);
2171         pthread_cond_signal(&client->replyq->cond);
2172         pthread_mutex_unlock(&client->replyq->mutex);
2173         debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2174         pthread_join(tlsserverwrth, NULL);
2175     }
2176     
2177  errexit:
2178     s = SSL_get_fd(ssl);
2179     SSL_free(ssl);
2180     shutdown(s, SHUT_RDWR);
2181     close(s);
2182     debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->conf->host);
2183     removeclient(client);
2184     pthread_exit(NULL);
2185 }
2186
2187 int tlslistener() {
2188     pthread_t tlsserverth;
2189     int s, snew;
2190     struct sockaddr_storage from;
2191     size_t fromlen = sizeof(from);
2192     struct clsrvconf *conf;
2193     struct client *client;
2194     struct clsrvconf *listenres;
2195     
2196     listenres = resolve_hostport('T', options.listentcp, DEFAULT_TLS_PORT);
2197     if ((s = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2198         debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
2199     
2200     listen(s, 0);
2201     debug(DBG_WARN, "listening for incoming TCP on %s:%s", listenres->host ? listenres->host : "*", listenres->port);
2202     free(listenres);
2203     
2204     for (;;) {
2205         snew = accept(s, (struct sockaddr *)&from, &fromlen);
2206         if (snew < 0) {
2207             debug(DBG_WARN, "accept failed");
2208             continue;
2209         }
2210         debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2211
2212         conf = find_conf('T', (struct sockaddr *)&from, clconfs, NULL);
2213         if (!conf) {
2214             debug(DBG_WARN, "ignoring request, not a known TLS client");
2215             shutdown(snew, SHUT_RDWR);
2216             close(snew);
2217             continue;
2218         }
2219
2220         client = addclient(conf);
2221
2222         if (!client) {
2223             debug(DBG_WARN, "Failed to create new client instance");
2224             shutdown(snew, SHUT_RDWR);
2225             close(snew);
2226             continue;
2227         }
2228         client->ssl = SSL_new(client->conf->ssl_ctx);
2229         SSL_set_fd(client->ssl, snew);
2230         if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
2231             debug(DBG_ERR, "tlslistener: pthread_create failed");
2232             SSL_free(client->ssl);
2233             removeclient(client);
2234             shutdown(snew, SHUT_RDWR);
2235             close(snew);
2236             continue;
2237         }
2238         pthread_detach(tlsserverth);
2239     }
2240     return 0;
2241 }
2242
2243 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
2244     struct tls *new;
2245     SSL_CTX *ctx;
2246     STACK_OF(X509_NAME) *calist;
2247     int i;
2248     unsigned long error;
2249     
2250     if (!certfile || !certkeyfile)
2251         debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2252
2253     if (!cacertfile && !cacertpath)
2254         debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2255
2256     if (!ssl_locks) {
2257         ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2258         ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2259         for (i = 0; i < CRYPTO_num_locks(); i++) {
2260             ssl_lock_count[i] = 0;
2261             pthread_mutex_init(&ssl_locks[i], NULL);
2262         }
2263         CRYPTO_set_id_callback(ssl_thread_id);
2264         CRYPTO_set_locking_callback(ssl_locking_callback);
2265
2266         SSL_load_error_strings();
2267         SSL_library_init();
2268
2269         while (!RAND_status()) {
2270             time_t t = time(NULL);
2271             pid_t pid = getpid();
2272             RAND_seed((unsigned char *)&t, sizeof(time_t));
2273             RAND_seed((unsigned char *)&pid, sizeof(pid));
2274         }
2275     }
2276     ctx = SSL_CTX_new(TLSv1_method());
2277     if (certkeypwd) {
2278         SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2279         SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2280     }
2281     if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2282         !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2283         !SSL_CTX_check_private_key(ctx) ||
2284         !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2285         while ((error = ERR_get_error()))
2286             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2287         debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2288     }
2289
2290     calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
2291     if (!cacertfile || calist) {
2292         if (cacertpath) {
2293             if (!calist)
2294                 calist = sk_X509_NAME_new_null();
2295             if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
2296                 sk_X509_NAME_free(calist);
2297                 calist = NULL;
2298             }
2299         }
2300     }
2301     if (!calist) {
2302         while ((error = ERR_get_error()))
2303             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2304         debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
2305     }
2306     SSL_CTX_set_client_CA_list(ctx, calist);
2307     
2308     SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2309     SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2310
2311     new = malloc(sizeof(struct tls));
2312     if (!new || !list_push(tlsconfs, new))
2313         debugx(1, DBG_ERR, "malloc failed");
2314
2315     memset(new, 0, sizeof(struct tls));
2316     new->name = stringcopy(value, 0);
2317     if (!new->name)
2318         debugx(1, DBG_ERR, "malloc failed");
2319     new->ctx = ctx;
2320     new->count = 0;
2321     debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2322 }
2323
2324 void tlsfree() {
2325     struct list_node *entry;
2326     struct tls *t;
2327     
2328     for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2329         t = (struct tls *)entry->data;
2330         if (t->name)
2331             free(t->name);
2332         if (!t->count)
2333             SSL_CTX_free(t->ctx);
2334     }
2335     list_destroy(tlsconfs);
2336     tlsconfs = NULL;
2337 }
2338
2339 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2340     struct list_node *entry;
2341     struct tls *t, *t1 = NULL, *t2 = NULL;
2342     
2343     for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2344         t = (struct tls *)entry->data;
2345         if (!strcasecmp(t->name, alt1)) {
2346             t1 = t;
2347             break;
2348         }
2349         if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2350             t2 = t;
2351     }
2352
2353     t = (t1 ? t1 : t2);
2354     if (!t)
2355         return NULL;
2356     t->count++;
2357     return t->ctx;
2358 }
2359
2360 void addrealm(char *value, char **servers, char *message) {
2361     int n;
2362     struct realm *realm;
2363     char *s, *regex = NULL;
2364     struct list_node *entry;
2365     struct clsrvconf *conf;
2366     
2367     if (*value == '/') {
2368         /* regexp, remove optional trailing / if present */
2369         if (value[strlen(value) - 1] == '/')
2370             value[strlen(value) - 1] = '\0';
2371     } else {
2372         /* not a regexp, let us make it one */
2373         if (*value == '*' && !value[1])
2374             regex = stringcopy(".*", 0);
2375         else {
2376             for (n = 0, s = value; *s;)
2377                 if (*s++ == '.')
2378                     n++;
2379             regex = malloc(strlen(value) + n + 3);
2380             if (regex) {
2381                 regex[0] = '@';
2382                 for (n = 1, s = value; *s; s++) {
2383                     if (*s == '.')
2384                         regex[n++] = '\\';
2385                     regex[n++] = *s;
2386                 }
2387                 regex[n++] = '$';
2388                 regex[n] = '\0';
2389             }
2390         }
2391         if (!regex)
2392             debugx(1, DBG_ERR, "malloc failed");
2393         debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2394     }
2395
2396     realm = malloc(sizeof(struct realm));
2397     if (!realm)
2398         debugx(1, DBG_ERR, "malloc failed");
2399     
2400     memset(realm, 0, sizeof(struct realm));
2401     realm->name = stringcopy(value, 0);
2402     if (!realm->name)
2403         debugx(1, DBG_ERR, "malloc failed");
2404     if (message && strlen(message) > 253)
2405         debugx(1, DBG_ERR, "ReplyMessage can be at most 253 bytes");
2406     realm->message = message;
2407     
2408     if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB))
2409         debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2410     if (regex)
2411         free(regex);
2412     
2413     if (servers && *servers) {
2414         realm->srvconfs = list_create();
2415         if (!realm->srvconfs)
2416             debugx(1, DBG_ERR, "malloc failed");
2417         for (n = 0; servers[n]; n++) {
2418             for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2419                 conf = (struct clsrvconf *)entry->data;
2420                 if (!strcasecmp(servers[n], conf->name))
2421                     break;
2422             }
2423             if (!entry)
2424                 debugx(1, DBG_ERR, "addrealm failed, no server %s", servers[n]);
2425             if (!list_push(realm->srvconfs, conf))
2426                 debugx(1, DBG_ERR, "malloc failed");
2427             debug(DBG_DBG, "addrealm: added server %s for realm %s", conf->name, value);
2428         }
2429     } else
2430         realm->srvconfs = NULL;
2431     
2432     if (!list_push(realms, realm))
2433         debugx(1, DBG_ERR, "malloc failed");
2434     debug(DBG_DBG, "addrealm: added realm %s", value);
2435 }
2436
2437 struct gconffile *openconfigfile(const char *filename) {
2438     FILE *f;
2439     char pathname[100], *base = NULL;
2440     struct gconffile *cf = NULL;
2441     
2442     f = pushgconffile(&cf, filename);
2443     if (f) {
2444         debug(DBG_DBG, "reading config file %s", filename);
2445         return cf;
2446     }
2447
2448     if (strlen(filename) + 1 <= sizeof(pathname)) {
2449         /* basename() might modify the string */
2450         strcpy(pathname, filename);
2451         base = basename(pathname);
2452         f = pushgconffile(&cf, base);
2453     }
2454
2455     if (!f)
2456         debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
2457     
2458     debug(DBG_DBG, "reading config file %s", base);
2459     return cf;
2460 }
2461
2462 int addmatchcertattr(struct clsrvconf *conf, char *matchcertattr) {
2463     char *v;
2464     
2465     v = matchcertattr + 20;
2466     if (strncasecmp(matchcertattr, "SubjectAltName:URI:/", 20) || !*v)
2467         return 0;
2468     /* regexp, remove optional trailing / if present */
2469     if (v[strlen(v) - 1] == '/')
2470         v[strlen(v) - 1] = '\0';
2471     if (!*v)
2472         return 0;
2473
2474     conf->certuriregex = malloc(sizeof(regex_t));
2475     if (!conf->certuriregex) {
2476         debug(DBG_ERR, "malloc failed");
2477         return 0;
2478     }
2479     if (regcomp(conf->certuriregex, v, REG_ICASE | REG_NOSUB)) {
2480         free(conf->certuriregex);
2481         conf->certuriregex = NULL;
2482         debug(DBG_ERR, "failed to compile regular expression %s", v);
2483         return 0;
2484     }
2485     return 1;
2486 }
2487
2488 int addrewriteattr(struct clsrvconf *conf, char *rewriteattr) {
2489     char *v, *w;
2490     
2491     v = rewriteattr + 11;
2492     if (strncasecmp(rewriteattr, "User-Name:/", 11) || !*v)
2493         return 0;
2494     /* regexp, remove optional trailing / if present */
2495     if (v[strlen(v) - 1] == '/')
2496         v[strlen(v) - 1] = '\0';
2497
2498     w = strchr(v, '/');
2499     if (!*w)
2500         return 0;
2501     *w = '\0';
2502     w++;
2503     
2504     conf->rewriteattrregex = malloc(sizeof(regex_t));
2505     if (!conf->rewriteattrregex) {
2506         debug(DBG_ERR, "malloc failed");
2507         return 0;
2508     }
2509
2510     conf->rewriteattrreplacement = stringcopy(w, 0);
2511     if (!conf->rewriteattrreplacement) {
2512         free(conf->rewriteattrregex);
2513         conf->rewriteattrregex = NULL;
2514         return 0;
2515     }
2516     
2517     if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
2518         free(conf->rewriteattrregex);
2519         conf->rewriteattrregex = NULL;
2520         free(conf->rewriteattrreplacement);
2521         conf->rewriteattrreplacement = NULL;
2522         debug(DBG_ERR, "failed to compile regular expression %s", v);
2523         return 0;
2524     }
2525
2526     return 1;
2527 }
2528
2529 void confclient_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2530     char *type = NULL, *tls = NULL, *matchcertattr = NULL, *rewriteattr = NULL;
2531     struct clsrvconf *conf;
2532     
2533     debug(DBG_DBG, "confclient_cb called for %s", block);
2534
2535     conf = malloc(sizeof(struct clsrvconf));
2536     if (!conf || !list_push(clconfs, conf))
2537         debugx(1, DBG_ERR, "malloc failed");
2538     memset(conf, 0, sizeof(struct clsrvconf));
2539     
2540     getgenericconfig(cf, block,
2541                      "type", CONF_STR, &type,
2542                      "host", CONF_STR, &conf->host,
2543                      "secret", CONF_STR, &conf->secret,
2544                      "tls", CONF_STR, &tls,
2545                      "matchcertificateattribute", CONF_STR, &matchcertattr,
2546                      "rewriteattribute", CONF_STR, &rewriteattr,
2547                      NULL
2548                      );
2549
2550     /* leave conf->name to be NULL for clients */
2551     if (!conf->host)
2552         conf->host = stringcopy(val, 0);
2553     
2554     if (type && !strcasecmp(type, "udp")) {
2555         conf->type = 'U';
2556         client_udp_count++;
2557     } else if (type && !strcasecmp(type, "tls")) {
2558         conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultclient", "default");
2559         if (!conf->ssl_ctx)
2560             debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2561         if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2562             debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2563         conf->type = 'T';
2564         client_tls_count++;
2565     } else
2566         debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2567     free(type);
2568     if (tls)
2569         free(tls);
2570     if (matchcertattr)
2571         free(matchcertattr);
2572     
2573     if (rewriteattr) {
2574         if (!addrewriteattr(conf, rewriteattr))
2575             debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2576         free(rewriteattr);
2577     }
2578     
2579     if (!resolvepeer(conf, 0))
2580         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2581     
2582     if (!conf->secret) {
2583         if (conf->type == 'U')
2584             debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2585         conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2586     }
2587 }
2588
2589 void confserver_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2590     char *type = NULL, *tls = NULL, *matchcertattr = NULL, *statusserver = NULL;
2591     struct clsrvconf *conf;
2592     
2593     debug(DBG_DBG, "confserver_cb called for %s", block);
2594
2595     conf = malloc(sizeof(struct clsrvconf));
2596     if (!conf || !list_push(srvconfs, conf))
2597         debugx(1, DBG_ERR, "malloc failed");
2598     memset(conf, 0, sizeof(struct clsrvconf));
2599     
2600     getgenericconfig(cf, block,
2601                      "type", CONF_STR, &type,
2602                      "host", CONF_STR, &conf->host,
2603                      "port", CONF_STR, &conf->port,
2604                      "secret", CONF_STR, &conf->secret,
2605                      "tls", CONF_STR, &tls,
2606                      "matchcertificateattribute", CONF_STR, &matchcertattr,
2607                      "StatusServer", CONF_STR, &statusserver,
2608                      NULL
2609                      );
2610
2611     conf->name = stringcopy(val, 0);
2612     if (!conf->host)
2613         conf->host = stringcopy(val, 0);
2614     
2615     if (type && !strcasecmp(type, "udp")) {
2616         conf->type = 'U';
2617         server_udp_count++;
2618         if (!conf->port)
2619             conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
2620     } else if (type && !strcasecmp(type, "tls")) {
2621         conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultserver", "default");
2622         if (!conf->ssl_ctx)
2623             debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2624         if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2625             debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2626         if (!conf->port)
2627             conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
2628         conf->type = 'T';
2629         server_tls_count++;
2630     } else
2631         debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2632     free(type);
2633     if (tls)
2634         free(tls);
2635     if (matchcertattr)
2636         free(matchcertattr);
2637     
2638     if (!resolvepeer(conf, 0))
2639         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2640     
2641     if (!conf->secret) {
2642         if (conf->type == 'U')
2643             debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2644         conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2645     }
2646     
2647     if (statusserver) {
2648         if (!strcasecmp(statusserver, "on"))
2649             conf->statusserver = 1;
2650         else if (strcasecmp(statusserver, "off"))
2651             debugx(1, DBG_ERR, "error in block %s, StatusServer is %s, must be on or off", block, statusserver);
2652         free(statusserver);
2653     }
2654 }
2655
2656 void confrealm_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2657     char **servers = NULL, *msg = NULL;
2658     
2659     debug(DBG_DBG, "confrealm_cb called for %s", block);
2660     
2661     getgenericconfig(cf, block,
2662                      "server", CONF_MSTR, &servers,
2663                      "ReplyMessage", CONF_STR, &msg,
2664                      NULL
2665                      );
2666
2667     addrealm(val, servers, msg);
2668     free(servers);
2669 }
2670
2671 void conftls_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2672     char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
2673     
2674     debug(DBG_DBG, "conftls_cb called for %s", block);
2675     
2676     getgenericconfig(cf, block,
2677                      "CACertificateFile", CONF_STR, &cacertfile,
2678                      "CACertificatePath", CONF_STR, &cacertpath,
2679                      "CertificateFile", CONF_STR, &certfile,
2680                      "CertificateKeyFile", CONF_STR, &certkeyfile,
2681                      "CertificateKeyPassword", CONF_STR, &certkeypwd,
2682                      NULL
2683                      );
2684     
2685     tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
2686     free(cacertfile);
2687     free(cacertpath);
2688     free(certfile);
2689     free(certkeyfile);
2690     free(certkeypwd);
2691 }
2692
2693 void getmainconfig(const char *configfile) {
2694     char *loglevel = NULL;
2695     struct gconffile *cfs;
2696
2697     cfs = openconfigfile(configfile);
2698     memset(&options, 0, sizeof(options));
2699     
2700     clconfs = list_create();
2701     if (!clconfs)
2702         debugx(1, DBG_ERR, "malloc failed");
2703     
2704     srvconfs = list_create();
2705     if (!srvconfs)
2706         debugx(1, DBG_ERR, "malloc failed");
2707     
2708     realms = list_create();
2709     if (!realms)
2710         debugx(1, DBG_ERR, "malloc failed");    
2711  
2712     tlsconfs = list_create();
2713     if (!tlsconfs)
2714         debugx(1, DBG_ERR, "malloc failed");    
2715  
2716     getgenericconfig(&cfs, NULL,
2717                      "ListenUDP", CONF_STR, &options.listenudp,
2718                      "ListenTCP", CONF_STR, &options.listentcp,
2719                      "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
2720                      "SourceUDP", CONF_STR, &options.sourceudp,
2721                      "SourceTCP", CONF_STR, &options.sourcetcp,
2722                      "LogLevel", CONF_STR, &loglevel,
2723                      "LogDestination", CONF_STR, &options.logdestination,
2724                      "Client", CONF_CBK, confclient_cb,
2725                      "Server", CONF_CBK, confserver_cb,
2726                      "Realm", CONF_CBK, confrealm_cb,
2727                      "TLS", CONF_CBK, conftls_cb,
2728                      NULL
2729                      );
2730     popgconffile(&cfs);
2731     tlsfree();
2732     
2733     if (loglevel) {
2734         if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
2735             debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
2736         options.loglevel = *loglevel - '0';
2737         free(loglevel);
2738     }
2739 }
2740
2741 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
2742     int c;
2743
2744     while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
2745         switch (c) {
2746         case 'c':
2747             *configfile = optarg;
2748             break;
2749         case 'd':
2750             if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
2751                 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
2752             *loglevel = *optarg - '0';
2753             break;
2754         case 'f':
2755             *foreground = 1;
2756             break;
2757         case 'p':
2758             *pretend = 1;
2759             break;
2760         case 'v':
2761                 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
2762         default:
2763             goto usage;
2764         }
2765     }
2766     if (!(argc - optind))
2767         return;
2768
2769  usage:
2770     debug(DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
2771     exit(1);
2772 }
2773
2774 #ifdef SYS_SOLARIS9
2775 int daemon(int a, int b) {
2776     int i;
2777
2778     if (fork())
2779         exit(0);
2780
2781     setsid();
2782
2783     for (i = 0; i < 3; i++) {
2784         close(i);
2785         open("/dev/null", O_RDWR);
2786     }
2787     return 1;
2788 }
2789 #endif
2790
2791 int main(int argc, char **argv) {
2792     pthread_t udpserverth, udpaccserverth, udpclient4rdth, udpclient6rdth;
2793     struct list_node *entry;
2794     uint8_t foreground = 0, pretend = 0, loglevel = 0;
2795     char *configfile = NULL;
2796     
2797     debug_init("radsecproxy");
2798     debug_set_level(DEBUG_LEVEL);
2799     getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
2800     if (loglevel)
2801         debug_set_level(loglevel);
2802     getmainconfig(configfile ? configfile : CONFIG_MAIN);
2803     if (loglevel)
2804         options.loglevel = loglevel;
2805     else if (options.loglevel)
2806         debug_set_level(options.loglevel);
2807     if (foreground)
2808         options.logdestination = NULL;
2809     else {
2810         if (!options.logdestination)
2811             options.logdestination = "x-syslog:///";
2812         debug_set_destination(options.logdestination);
2813     }
2814
2815     if (pretend)
2816         debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
2817     
2818     if (!list_first(clconfs))
2819         debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
2820     if (!list_first(srvconfs))
2821         debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
2822     if (!list_first(realms))
2823         debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
2824
2825     if (!foreground && (daemon(0, 0) < 0))
2826         debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
2827     
2828     debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
2829
2830     if (client_udp_count) {
2831         udp_server_replyq = newreplyq();
2832         if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
2833             debugx(1, DBG_ERR, "pthread_create failed");
2834         if (options.listenaccudp)
2835             if (pthread_create(&udpaccserverth, NULL, udpaccserverrd, NULL))
2836                 debugx(1, DBG_ERR, "pthread_create failed");
2837     }
2838     
2839     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2840         addserver((struct clsrvconf *)entry->data);
2841         if (pthread_create(&((struct clsrvconf *)entry->data)->servers->clientth, NULL, clientwr,
2842                            (void *)((struct clsrvconf *)entry->data)->servers))
2843             debugx(1, DBG_ERR, "pthread_create failed");
2844     }
2845     /* srcudpres no longer needed, while srctcpres is needed later */
2846     if (srcudpres) {
2847         free(srcudpres);
2848         srcudpres = NULL;
2849     }
2850     if (udp_client4_sock >= 0)
2851         if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
2852             debugx(1, DBG_ERR, "clientwr: pthread_create failed");
2853     if (udp_client6_sock >= 0)
2854         if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
2855             debugx(1, DBG_ERR, "clientwr: pthread_create failed");
2856     
2857     if (client_tls_count)
2858         return tlslistener();
2859     
2860     /* just hang around doing nothing, anything to do here? */
2861     for (;;)
2862         sleep(1000);
2863 }