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