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