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