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