better status-server debug output
[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) {
675     while (length > 1) {
676         if (ATTRTYPE(attrs) == type)
677             return attrs;
678         length -= ATTRLEN(attrs);
679         attrs += ATTRLEN(attrs);
680     }
681     return NULL;
682 }
683
684 void sendrq(struct server *to, struct request *rq) {
685     int i;
686     uint8_t *attr;
687
688     pthread_mutex_lock(&to->newrq_mutex);
689     /* might simplify if only try nextid, might be ok */
690     for (i = to->nextid; i < MAX_REQUESTS; i++)
691         if (!to->requests[i].buf)
692             break;
693     if (i == MAX_REQUESTS) {
694         for (i = 0; i < to->nextid; i++)
695             if (!to->requests[i].buf)
696                 break;
697         if (i == to->nextid) {
698             debug(DBG_WARN, "No room in queue, dropping request");
699             free(rq->buf);
700             pthread_mutex_unlock(&to->newrq_mutex);
701             return;
702         }
703     }
704     
705     rq->buf[1] = (char)i;
706
707     attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
708     if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->peer.secret)) {
709         free(rq->buf);
710         pthread_mutex_unlock(&to->newrq_mutex);
711         return;
712     }
713
714     debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->peer.host);
715     to->requests[i] = *rq;
716     to->nextid = i + 1;
717
718     if (!to->newrq) {
719         to->newrq = 1;
720         debug(DBG_DBG, "signalling client writer");
721         pthread_cond_signal(&to->newrq_cond);
722     }
723     pthread_mutex_unlock(&to->newrq_mutex);
724 }
725
726 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
727     struct replyq *replyq = to->replyq;
728     
729     if (!radsign(buf, (unsigned char *)to->peer.secret)) {
730         free(buf);
731         debug(DBG_WARN, "sendreply: failed to sign message");
732         return;
733     }
734         
735     pthread_mutex_lock(&replyq->count_mutex);
736     if (replyq->count == replyq->size) {
737         debug(DBG_WARN, "No room in queue, dropping request");
738         pthread_mutex_unlock(&replyq->count_mutex);
739         free(buf);
740         return;
741     }
742
743     replyq->replies[replyq->count].buf = buf;
744     if (tosa)
745         replyq->replies[replyq->count].tosa = *tosa;
746     replyq->count++;
747
748     if (replyq->count == 1) {
749         debug(DBG_DBG, "signalling client writer");
750         pthread_cond_signal(&replyq->count_cond);
751     }
752     pthread_mutex_unlock(&replyq->count_mutex);
753 }
754
755 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
756     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
757     static unsigned char first = 1;
758     static EVP_MD_CTX mdctx;
759     unsigned char hash[EVP_MAX_MD_SIZE], *input;
760     unsigned int md_len;
761     uint8_t i, offset = 0, out[128];
762     
763     pthread_mutex_lock(&lock);
764     if (first) {
765         EVP_MD_CTX_init(&mdctx);
766         first = 0;
767     }
768
769     input = auth;
770     for (;;) {
771         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
772             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
773             !EVP_DigestUpdate(&mdctx, input, 16) ||
774             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
775             md_len != 16) {
776             pthread_mutex_unlock(&lock);
777             return 0;
778         }
779         for (i = 0; i < 16; i++)
780             out[offset + i] = hash[i] ^ in[offset + i];
781         input = out + offset - 16;
782         offset += 16;
783         if (offset == len)
784             break;
785     }
786     memcpy(in, out, len);
787     pthread_mutex_unlock(&lock);
788     return 1;
789 }
790
791 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
792     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
793     static unsigned char first = 1;
794     static EVP_MD_CTX mdctx;
795     unsigned char hash[EVP_MAX_MD_SIZE], *input;
796     unsigned int md_len;
797     uint8_t i, offset = 0, out[128];
798     
799     pthread_mutex_lock(&lock);
800     if (first) {
801         EVP_MD_CTX_init(&mdctx);
802         first = 0;
803     }
804
805     input = auth;
806     for (;;) {
807         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
808             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
809             !EVP_DigestUpdate(&mdctx, input, 16) ||
810             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
811             md_len != 16) {
812             pthread_mutex_unlock(&lock);
813             return 0;
814         }
815         for (i = 0; i < 16; i++)
816             out[offset + i] = hash[i] ^ in[offset + i];
817         input = in + offset;
818         offset += 16;
819         if (offset == len)
820             break;
821     }
822     memcpy(in, out, len);
823     pthread_mutex_unlock(&lock);
824     return 1;
825 }
826
827 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
828     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
829     static unsigned char first = 1;
830     static EVP_MD_CTX mdctx;
831     unsigned char hash[EVP_MAX_MD_SIZE];
832     unsigned int md_len;
833     uint8_t i, offset;
834     
835     pthread_mutex_lock(&lock);
836     if (first) {
837         EVP_MD_CTX_init(&mdctx);
838         first = 0;
839     }
840
841 #if 0    
842     printf("msppencrypt auth in: ");
843     for (i = 0; i < 16; i++)
844         printf("%02x ", auth[i]);
845     printf("\n");
846     
847     printf("msppencrypt salt in: ");
848     for (i = 0; i < 2; i++)
849         printf("%02x ", salt[i]);
850     printf("\n");
851     
852     printf("msppencrypt in: ");
853     for (i = 0; i < len; i++)
854         printf("%02x ", text[i]);
855     printf("\n");
856 #endif
857     
858     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
859         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
860         !EVP_DigestUpdate(&mdctx, auth, 16) ||
861         !EVP_DigestUpdate(&mdctx, salt, 2) ||
862         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
863         pthread_mutex_unlock(&lock);
864         return 0;
865     }
866
867 #if 0    
868     printf("msppencrypt hash: ");
869     for (i = 0; i < 16; i++)
870         printf("%02x ", hash[i]);
871     printf("\n");
872 #endif
873     
874     for (i = 0; i < 16; i++)
875         text[i] ^= hash[i];
876     
877     for (offset = 16; offset < len; offset += 16) {
878 #if 0   
879         printf("text + offset - 16 c(%d): ", offset / 16);
880         for (i = 0; i < 16; i++)
881             printf("%02x ", (text + offset - 16)[i]);
882         printf("\n");
883 #endif
884         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
885             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
886             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
887             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
888             md_len != 16) {
889             pthread_mutex_unlock(&lock);
890             return 0;
891         }
892 #if 0   
893         printf("msppencrypt hash: ");
894         for (i = 0; i < 16; i++)
895             printf("%02x ", hash[i]);
896         printf("\n");
897 #endif    
898         
899         for (i = 0; i < 16; i++)
900             text[offset + i] ^= hash[i];
901     }
902     
903 #if 0
904     printf("msppencrypt out: ");
905     for (i = 0; i < len; i++)
906         printf("%02x ", text[i]);
907     printf("\n");
908 #endif
909
910     pthread_mutex_unlock(&lock);
911     return 1;
912 }
913
914 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
915     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
916     static unsigned char first = 1;
917     static EVP_MD_CTX mdctx;
918     unsigned char hash[EVP_MAX_MD_SIZE];
919     unsigned int md_len;
920     uint8_t i, offset;
921     char plain[255];
922     
923     pthread_mutex_lock(&lock);
924     if (first) {
925         EVP_MD_CTX_init(&mdctx);
926         first = 0;
927     }
928
929 #if 0    
930     printf("msppdecrypt auth in: ");
931     for (i = 0; i < 16; i++)
932         printf("%02x ", auth[i]);
933     printf("\n");
934     
935     printf("msppedecrypt salt in: ");
936     for (i = 0; i < 2; i++)
937         printf("%02x ", salt[i]);
938     printf("\n");
939     
940     printf("msppedecrypt in: ");
941     for (i = 0; i < len; i++)
942         printf("%02x ", text[i]);
943     printf("\n");
944 #endif
945     
946     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
947         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
948         !EVP_DigestUpdate(&mdctx, auth, 16) ||
949         !EVP_DigestUpdate(&mdctx, salt, 2) ||
950         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
951         pthread_mutex_unlock(&lock);
952         return 0;
953     }
954
955 #if 0    
956     printf("msppedecrypt hash: ");
957     for (i = 0; i < 16; i++)
958         printf("%02x ", hash[i]);
959     printf("\n");
960 #endif
961     
962     for (i = 0; i < 16; i++)
963         plain[i] = text[i] ^ hash[i];
964     
965     for (offset = 16; offset < len; offset += 16) {
966 #if 0   
967         printf("text + offset - 16 c(%d): ", offset / 16);
968         for (i = 0; i < 16; i++)
969             printf("%02x ", (text + offset - 16)[i]);
970         printf("\n");
971 #endif
972         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
973             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
974             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
975             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
976             md_len != 16) {
977             pthread_mutex_unlock(&lock);
978             return 0;
979         }
980 #if 0   
981     printf("msppedecrypt hash: ");
982     for (i = 0; i < 16; i++)
983         printf("%02x ", hash[i]);
984     printf("\n");
985 #endif    
986
987     for (i = 0; i < 16; i++)
988         plain[offset + i] = text[offset + i] ^ hash[i];
989     }
990
991     memcpy(text, plain, len);
992 #if 0
993     printf("msppedecrypt out: ");
994     for (i = 0; i < len; i++)
995         printf("%02x ", text[i]);
996     printf("\n");
997 #endif
998
999     pthread_mutex_unlock(&lock);
1000     return 1;
1001 }
1002
1003 struct server *id2server(char *id, uint8_t len) {
1004     int i;
1005     for (i = 0; i < realm_count; i++)
1006         if (!regexec(&realms[i].regex, id, 0, NULL, 0)) {
1007             debug(DBG_DBG, "found matching realm: %s, host %s", realms[i].name, realms[i].server->peer.host);
1008             return realms[i].server;
1009         }
1010     return NULL;
1011 }
1012
1013 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
1014     int i;
1015     
1016     pthread_mutex_lock(&to->newrq_mutex);
1017     for (i = 0; i < MAX_REQUESTS; i++)
1018         if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
1019             break;
1020     pthread_mutex_unlock(&to->newrq_mutex);
1021     
1022     return i < MAX_REQUESTS;
1023 }
1024
1025 int attrvalidate(unsigned char *attrs, int length) {
1026     while (length > 1) {
1027         if (ATTRLEN(attrs) < 2) {
1028             debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1029             return 0;
1030         }
1031         length -= ATTRLEN(attrs);
1032         if (length < 0) {
1033             debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1034             return 0;
1035         }
1036         attrs += ATTRLEN(attrs);
1037     }
1038     if (length)
1039         debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1040     return 1;
1041 }
1042
1043 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1044 #ifdef DEBUG    
1045     int i;
1046 #endif    
1047     if (len < 16 || len > 128 || len % 16) {
1048         debug(DBG_WARN, "pwdrecrypt: invalid password length");
1049         return 0;
1050     }
1051         
1052     if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1053         debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1054         return 0;
1055     }
1056 #ifdef DEBUG
1057     printf("pwdrecrypt: password: ");
1058     for (i = 0; i < len; i++)
1059         printf("%02x ", pwd[i]);
1060     printf("\n");
1061 #endif  
1062     if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1063         debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1064         return 0;
1065     }
1066     return 1;
1067 }
1068
1069 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1070     if (len < 18)
1071         return 0;
1072     if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1073         debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1074         return 0;
1075     }
1076     if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1077         debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1078         return 0;
1079     }
1080     return 1;
1081 }
1082
1083 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1084            char *oldsecret, char *newsecret) {
1085     unsigned char *attr;
1086     
1087     for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1088         debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1089         if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1090             return 0;
1091     }
1092     return 1;
1093 }
1094
1095 void respondstatusserver(struct request *rq) {
1096     unsigned char *resp;
1097
1098     resp = malloc(20);
1099     if (!resp) {
1100         debug(DBG_ERR, "respondstatusserver: malloc failed");
1101         return;
1102     }
1103     memcpy(resp, rq->buf, 20);
1104     resp[0] = RAD_Access_Accept;
1105     resp[2] = 0;
1106     resp[3] = 20;
1107     debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->peer.host);
1108     sendreply(rq->from, resp, rq->from->peer.type == 'U' ? &rq->fromsa : NULL);
1109 }
1110
1111 void radsrv(struct request *rq) {
1112     uint8_t code, id, *auth, *attrs, *attr;
1113     uint16_t len;
1114     struct server *to;
1115     char username[256];
1116     unsigned char *buf, newauth[16];
1117
1118     buf = rq->buf;
1119     code = *(uint8_t *)buf;
1120     id = *(uint8_t *)(buf + 1);
1121     len = RADLEN(buf);
1122     auth = (uint8_t *)(buf + 4);
1123
1124     debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1125     
1126     if (code != RAD_Access_Request && code != RAD_Status_Server) {
1127         debug(DBG_INFO, "radsrv: server currently accepts only access-requests and status-server, ignoring");
1128         free(buf);
1129         return;
1130     }
1131
1132     len -= 20;
1133     attrs = buf + 20;
1134
1135     if (!attrvalidate(attrs, len)) {
1136         debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1137         free(buf);
1138         return;
1139     }
1140
1141     if (code == RAD_Access_Request) {
1142         attr = attrget(attrs, len, RAD_Attr_User_Name);
1143         if (!attr) {
1144             debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1145             free(buf);
1146             return;
1147         }
1148         memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1149         username[ATTRVALLEN(attr)] = '\0';
1150         debug(DBG_DBG, "Access Request with username: %s", username);
1151     
1152         to = id2server(username, strlen(username));
1153         if (!to) {
1154             debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1155             free(buf);
1156             return;
1157         }
1158     
1159         if (rqinqueue(to, rq->from, id)) {
1160             debug(DBG_INFO, "radsrv: already got request from host %s with id %d, ignoring", rq->from->peer.host, id);
1161             free(buf);
1162             return;
1163         }
1164     }
1165     
1166     attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1167     if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(buf, ATTRVAL(attr), rq->from->peer.secret))) {
1168         debug(DBG_WARN, "radsrv: message authentication failed");
1169         free(buf);
1170         return;
1171     }
1172     
1173     if (code == RAD_Status_Server) {
1174         respondstatusserver(rq);
1175         return;
1176     }
1177     
1178     if (!RAND_bytes(newauth, 16)) {
1179         debug(DBG_WARN, "radsrv: failed to generate random auth");
1180         free(buf);
1181         return;
1182     }
1183
1184 #ifdef DEBUG    
1185     printauth("auth", auth);
1186 #endif
1187
1188     attr = attrget(attrs, len, RAD_Attr_User_Password);
1189     if (attr) {
1190         debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1191         if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->peer.secret, to->peer.secret, auth, newauth)) {
1192             free(buf);
1193             return;
1194         }
1195     }
1196     
1197     attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1198     if (attr) {
1199         debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1200         if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->peer.secret, to->peer.secret, auth, newauth)) {
1201             free(buf);
1202             return;
1203         }
1204     }
1205
1206     rq->origid = id;
1207     memcpy(rq->origauth, auth, 16);
1208     memcpy(auth, newauth, 16);
1209     sendrq(to, rq);
1210 }
1211
1212 void *clientrd(void *arg) {
1213     struct server *server = (struct server *)arg;
1214     struct client *from;
1215     int i, len, sublen;
1216     unsigned char *buf, *messageauth, *subattrs, *attrs, *attr;
1217     struct sockaddr_storage fromsa;
1218     struct timeval lastconnecttry;
1219     char tmp[256];
1220     
1221     for (;;) {
1222         lastconnecttry = server->lastconnecttry;
1223         buf = (server->peer.type == 'U' ? radudpget(server->sock, NULL, &server, NULL) : radtlsget(server->peer.ssl));
1224         if (!buf && server->peer.type == 'T') {
1225             tlsconnect(server, &lastconnecttry, "clientrd");
1226             continue;
1227         }
1228     
1229         server->connectionok = 1;
1230
1231         i = buf[1]; /* i is the id */
1232
1233         switch (*buf) {
1234         case RAD_Access_Accept:
1235             debug(DBG_DBG, "got Access Accept with id %d", i);
1236             break;
1237         case RAD_Access_Reject:
1238             debug(DBG_DBG, "got Access Reject with id %d", i);
1239             break;
1240         case RAD_Access_Challenge:
1241             debug(DBG_DBG, "got Access Challenge with id %d", i);
1242             break;
1243         default:
1244             free(buf);
1245             debug(DBG_INFO, "clientrd: discarding, only accept access accept, access reject and access challenge messages");
1246             continue;
1247         }
1248         
1249         pthread_mutex_lock(&server->newrq_mutex);
1250         if (!server->requests[i].buf || !server->requests[i].tries) {
1251             pthread_mutex_unlock(&server->newrq_mutex);
1252             free(buf);
1253             debug(DBG_INFO, "clientrd: no matching request sent with this id, ignoring");
1254             continue;
1255         }
1256
1257         if (server->requests[i].received) {
1258             pthread_mutex_unlock(&server->newrq_mutex);
1259             free(buf);
1260             debug(DBG_INFO, "clientrd: already received, ignoring");
1261             continue;
1262         }
1263         
1264         if (!validauth(buf, server->requests[i].buf + 4, (unsigned char *)server->peer.secret)) {
1265             pthread_mutex_unlock(&server->newrq_mutex);
1266             free(buf);
1267             debug(DBG_WARN, "clientrd: invalid auth, ignoring");
1268             continue;
1269         }
1270         
1271         from = server->requests[i].from;
1272         len = RADLEN(buf) - 20;
1273         attrs = buf + 20;
1274
1275         if (!attrvalidate(attrs, len)) {
1276             pthread_mutex_unlock(&server->newrq_mutex);
1277             free(buf);
1278             debug(DBG_WARN, "clientrd: attribute validation failed, ignoring packet");
1279             continue;
1280         }
1281         
1282         /* Message Authenticator */
1283         messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1284         if (messageauth) {
1285             if (ATTRVALLEN(messageauth) != 16) {
1286                 pthread_mutex_unlock(&server->newrq_mutex);
1287                 free(buf);
1288                 debug(DBG_WARN, "clientrd: illegal message auth attribute length, ignoring packet");
1289                 continue;
1290             }
1291             memcpy(tmp, buf + 4, 16);
1292             memcpy(buf + 4, server->requests[i].buf + 4, 16);
1293             if (!checkmessageauth(buf, ATTRVAL(messageauth), server->peer.secret)) {
1294                 pthread_mutex_unlock(&server->newrq_mutex);
1295                 free(buf);
1296                 debug(DBG_WARN, "clientrd: message authentication failed");
1297                 continue;
1298             }
1299             memcpy(buf + 4, tmp, 16);
1300             debug(DBG_DBG, "clientrd: message auth ok");
1301         }
1302         
1303         if (*server->requests[i].buf == RAD_Status_Server) {
1304             server->requests[i].received = 1;
1305             pthread_mutex_unlock(&server->newrq_mutex);
1306             free(buf);
1307             debug(DBG_INFO, "clientrd: got status server response from %s", server->peer.host);
1308             continue;
1309         }
1310
1311         /* MS MPPE */
1312         for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1313             if (ATTRVALLEN(attr) <= 4)
1314                 break;
1315             
1316             if (((uint16_t *)attr)[1] != 0 || ntohs(((uint16_t *)attr)[2]) != 311) /* 311 == MS */
1317                 continue;
1318             
1319             sublen = ATTRVALLEN(attr) - 4;
1320             subattrs = ATTRVAL(attr) + 4;  
1321             if (!attrvalidate(subattrs, sublen) ||
1322                 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1323                         server->requests + i, server->peer.secret, from->peer.secret) ||
1324                 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1325                         server->requests + i, server->peer.secret, from->peer.secret))
1326                 break;
1327         }
1328         if (attr) {
1329             pthread_mutex_unlock(&server->newrq_mutex);
1330             free(buf);
1331             debug(DBG_WARN, "clientrd: MS attribute handling failed, ignoring packet");
1332             continue;
1333         }
1334         
1335         if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject) {
1336             attr = attrget(server->requests[i].buf + 20, RADLEN(server->requests[i].buf) - 20, RAD_Attr_User_Name);
1337             /* we know the attribute exists */
1338             memcpy(tmp, ATTRVAL(attr), ATTRVALLEN(attr));
1339             tmp[ATTRVALLEN(attr)] = '\0';
1340             switch (*buf) {
1341             case RAD_Access_Accept:
1342                 debug(DBG_INFO, "Access Accept for %s from %s", tmp, server->peer.host);
1343                 break;
1344             case RAD_Access_Reject:
1345                 debug(DBG_INFO, "Access Reject for %s from %s", tmp, server->peer.host);
1346                 break;
1347             }
1348         }
1349         
1350         /* once we set received = 1, requests[i] may be reused */
1351         buf[1] = (char)server->requests[i].origid;
1352         memcpy(buf + 4, server->requests[i].origauth, 16);
1353 #ifdef DEBUG    
1354         printauth("origauth/buf+4", buf + 4);
1355 #endif
1356         
1357         if (messageauth) {
1358             if (!createmessageauth(buf, ATTRVAL(messageauth), from->peer.secret)) {
1359                 pthread_mutex_unlock(&server->newrq_mutex);
1360                 free(buf);
1361                 continue;
1362             }
1363             debug(DBG_DBG, "clientrd: computed messageauthattr");
1364         }
1365
1366         if (from->peer.type == 'U')
1367             fromsa = server->requests[i].fromsa;
1368         server->requests[i].received = 1;
1369         pthread_mutex_unlock(&server->newrq_mutex);
1370
1371         debug(DBG_DBG, "clientrd: giving packet back to where it came from");
1372         sendreply(from, buf, from->peer.type == 'U' ? &fromsa : NULL);
1373     }
1374 }
1375
1376 void *clientwr(void *arg) {
1377     struct server *server = (struct server *)arg;
1378     struct request *rq;
1379     pthread_t clientrdth;
1380     int i;
1381     uint8_t rnd;
1382     struct timeval now, lastsend;
1383     struct timespec timeout;
1384     struct request statsrvrq;
1385     unsigned char statsrvbuf[38];
1386
1387     memset(&timeout, 0, sizeof(struct timespec));
1388     
1389     if (server->statusserver) {
1390         memset(&statsrvrq, 0, sizeof(struct request));
1391         memset(statsrvbuf, 0, sizeof(statsrvbuf));
1392         statsrvbuf[0] = RAD_Status_Server;
1393         statsrvbuf[3] = 38;
1394         statsrvbuf[20] = RAD_Attr_Message_Authenticator;
1395         statsrvbuf[21] = 18;
1396         gettimeofday(&lastsend, NULL);
1397     }
1398     
1399     if (server->peer.type == 'U') {
1400         if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0)
1401             debugx(1, DBG_ERR, "clientwr: connecttoserver failed");
1402     } else
1403         tlsconnect(server, NULL, "new client");
1404     
1405     if (pthread_create(&clientrdth, NULL, clientrd, (void *)server))
1406         debugx(1, DBG_ERR, "clientwr: pthread_create failed");
1407
1408     for (;;) {
1409         pthread_mutex_lock(&server->newrq_mutex);
1410         if (!server->newrq) {
1411             gettimeofday(&now, NULL);
1412             if (server->statusserver) {
1413                 /* random 0-7 seconds */
1414                 RAND_bytes(&rnd, 1);
1415                 rnd /= 32;
1416                 if (!timeout.tv_sec || timeout.tv_sec - now.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
1417                     timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
1418             }   
1419             if (timeout.tv_sec) {
1420                 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1421                 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1422                 timeout.tv_sec = 0;
1423             } else {
1424                 debug(DBG_DBG, "clientwr: waiting for new request");
1425                 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1426             }
1427         }
1428         if (server->newrq) {
1429             debug(DBG_DBG, "clientwr: got new request");
1430             server->newrq = 0;
1431         } else
1432             debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1433         pthread_mutex_unlock(&server->newrq_mutex);
1434
1435         for (i = 0; i < MAX_REQUESTS; i++) {
1436             pthread_mutex_lock(&server->newrq_mutex);
1437             while (!server->requests[i].buf && i < MAX_REQUESTS)
1438                 i++;
1439             if (i == MAX_REQUESTS) {
1440                 pthread_mutex_unlock(&server->newrq_mutex);
1441                 break;
1442             }
1443             rq = server->requests + i;
1444
1445             if (rq->received) {
1446                 debug(DBG_DBG, "clientwr: removing received packet from queue");
1447                 free(rq->buf);
1448                 /* setting this to NULL means that it can be reused */
1449                 rq->buf = NULL;
1450                 pthread_mutex_unlock(&server->newrq_mutex);
1451                 continue;
1452             }
1453             
1454             gettimeofday(&now, NULL);
1455             if (now.tv_sec < rq->expiry.tv_sec) {
1456                 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1457                     timeout.tv_sec = rq->expiry.tv_sec;
1458                 pthread_mutex_unlock(&server->newrq_mutex);
1459                 continue;
1460             }
1461
1462             if (rq->tries == (*rq->buf == RAD_Status_Server || server->peer.type == 'T'
1463                               ? 1 : REQUEST_RETRIES)) {
1464                 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1465                 if (*rq->buf == RAD_Status_Server)
1466                     debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->peer.host);
1467                 free(rq->buf);
1468                 /* setting this to NULL means that it can be reused */
1469                 rq->buf = NULL;
1470                 pthread_mutex_unlock(&server->newrq_mutex);
1471                 continue;
1472             }
1473             pthread_mutex_unlock(&server->newrq_mutex);
1474
1475             rq->expiry.tv_sec = now.tv_sec +
1476                 (*rq->buf == RAD_Status_Server || server->peer.type == 'T'
1477                  ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
1478             if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1479                 timeout.tv_sec = rq->expiry.tv_sec;
1480             rq->tries++;
1481             clientradput(server, server->requests[i].buf);
1482             gettimeofday(&lastsend, NULL);
1483             usleep(200000);
1484         }
1485         if (server->statusserver) {
1486             gettimeofday(&now, NULL);
1487             if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
1488                 if (!RAND_bytes(statsrvbuf + 4, 16)) {
1489                     debug(DBG_WARN, "clientwr: failed to generate random auth");
1490                     continue;
1491                 }
1492                 statsrvrq.buf = malloc(sizeof(statsrvbuf));
1493                 if (!statsrvrq.buf) {
1494                     debug(DBG_ERR, "clientwr: malloc failed");
1495                     continue;
1496                 }
1497                 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
1498                 debug(DBG_DBG, "clientwr: sending status server to %s", server->peer.host);
1499                 lastsend.tv_sec = now.tv_sec;
1500                 sendrq(server, &statsrvrq);
1501             }
1502         }
1503     }
1504 }
1505
1506 void *udpserverwr(void *arg) {
1507     struct replyq *replyq = &udp_server_replyq;
1508     struct reply *reply = replyq->replies;
1509     
1510     pthread_mutex_lock(&replyq->count_mutex);
1511     for (;;) {
1512         while (!replyq->count) {
1513             debug(DBG_DBG, "udp server writer, waiting for signal");
1514             pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1515             debug(DBG_DBG, "udp server writer, got signal");
1516         }
1517         pthread_mutex_unlock(&replyq->count_mutex);
1518         
1519         if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
1520                    (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
1521             debug(DBG_WARN, "sendudp: send failed");
1522         free(reply->buf);
1523         
1524         pthread_mutex_lock(&replyq->count_mutex);
1525         replyq->count--;
1526         memmove(replyq->replies, replyq->replies + 1,
1527                 replyq->count * sizeof(struct reply));
1528     }
1529 }
1530
1531 void *udpserverrd(void *arg) {
1532     struct request rq;
1533     pthread_t udpserverwrth;
1534
1535     if ((udp_server_sock = bindtoaddr(udp_server_listen->addrinfo)) < 0)
1536         debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
1537
1538     debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
1539           udp_server_listen->host ? udp_server_listen->host : "*", udp_server_listen->port);
1540
1541     if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
1542         debugx(1, DBG_ERR, "pthread_create failed");
1543     
1544     for (;;) {
1545         memset(&rq, 0, sizeof(struct request));
1546         rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
1547         radsrv(&rq);
1548     }
1549 }
1550
1551 void *tlsserverwr(void *arg) {
1552     int cnt;
1553     unsigned long error;
1554     struct client *client = (struct client *)arg;
1555     struct replyq *replyq;
1556     
1557     debug(DBG_DBG, "tlsserverwr starting for %s", client->peer.host);
1558     replyq = client->replyq;
1559     pthread_mutex_lock(&replyq->count_mutex);
1560     for (;;) {
1561         while (!replyq->count) {
1562             if (client->peer.ssl) {         
1563                 debug(DBG_DBG, "tls server writer, waiting for signal");
1564                 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1565                 debug(DBG_DBG, "tls server writer, got signal");
1566             }
1567             if (!client->peer.ssl) {
1568                 /* ssl might have changed while waiting */
1569                 pthread_mutex_unlock(&replyq->count_mutex);
1570                 debug(DBG_DBG, "tlsserverwr: exiting as requested");
1571                 pthread_exit(NULL);
1572             }
1573         }
1574         pthread_mutex_unlock(&replyq->count_mutex);
1575         cnt = SSL_write(client->peer.ssl, replyq->replies->buf, RADLEN(replyq->replies->buf));
1576         if (cnt > 0)
1577             debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
1578                   cnt, RADLEN(replyq->replies->buf));
1579         else
1580             while ((error = ERR_get_error()))
1581                 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
1582         free(replyq->replies->buf);
1583
1584         pthread_mutex_lock(&replyq->count_mutex);
1585         replyq->count--;
1586         memmove(replyq->replies, replyq->replies + 1, replyq->count * sizeof(struct reply));
1587     }
1588 }
1589
1590 void *tlsserverrd(void *arg) {
1591     struct request rq;
1592     unsigned long error;
1593     int s;
1594     struct client *client = (struct client *)arg;
1595     pthread_t tlsserverwrth;
1596     SSL *ssl;
1597     
1598     debug(DBG_DBG, "tlsserverrd starting for %s", client->peer.host);
1599     ssl = client->peer.ssl;
1600
1601     if (SSL_accept(ssl) <= 0) {
1602         while ((error = ERR_get_error()))
1603             debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
1604         debug(DBG_ERR, "SSL_accept failed");
1605         goto errexit;
1606     }
1607     if (tlsverifycert(&client->peer)) {
1608         if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
1609             debug(DBG_ERR, "tlsserverrd: pthread_create failed");
1610             goto errexit;
1611         }
1612         for (;;) {
1613             memset(&rq, 0, sizeof(struct request));
1614             rq.buf = radtlsget(client->peer.ssl);
1615             if (!rq.buf)
1616                 break;
1617             debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->peer.host);
1618             rq.from = client;
1619             radsrv(&rq);
1620         }
1621         debug(DBG_ERR, "tlsserverrd: connection lost");
1622         /* stop writer by setting peer.ssl to NULL and give signal in case waiting for data */
1623         client->peer.ssl = NULL;
1624         pthread_mutex_lock(&client->replyq->count_mutex);
1625         pthread_cond_signal(&client->replyq->count_cond);
1626         pthread_mutex_unlock(&client->replyq->count_mutex);
1627         debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
1628         pthread_join(tlsserverwrth, NULL);
1629     }
1630     
1631  errexit:
1632     s = SSL_get_fd(ssl);
1633     SSL_free(ssl);
1634     shutdown(s, SHUT_RDWR);
1635     close(s);
1636     debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->peer.host);
1637     client->peer.ssl = NULL;
1638     pthread_exit(NULL);
1639 }
1640
1641 int tlslistener() {
1642     pthread_t tlsserverth;
1643     int s, snew;
1644     struct sockaddr_storage from;
1645     size_t fromlen = sizeof(from);
1646     struct client *client;
1647
1648     if ((s = bindtoaddr(tcp_server_listen->addrinfo)) < 0)
1649         debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
1650     
1651     listen(s, 0);
1652     debug(DBG_WARN, "listening for incoming TCP on %s:%s",
1653           tcp_server_listen->host ? tcp_server_listen->host : "*", tcp_server_listen->port);
1654
1655     for (;;) {
1656         snew = accept(s, (struct sockaddr *)&from, &fromlen);
1657         if (snew < 0) {
1658             debug(DBG_WARN, "accept failed");
1659             continue;
1660         }
1661         debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
1662
1663         client = find_client('T', (struct sockaddr *)&from, NULL);
1664         if (!client) {
1665             debug(DBG_WARN, "ignoring request, not a known TLS client");
1666             shutdown(snew, SHUT_RDWR);
1667             close(snew);
1668             continue;
1669         }
1670
1671         if (client->peer.ssl) {
1672             debug(DBG_WARN, "Ignoring incoming TLS connection, already have one from this client");
1673             shutdown(snew, SHUT_RDWR);
1674             close(snew);
1675             continue;
1676         }
1677         client->peer.ssl = SSL_new(ssl_ctx);
1678         SSL_set_fd(client->peer.ssl, snew);
1679         if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
1680             debug(DBG_ERR, "tlslistener: pthread_create failed");
1681             SSL_free(client->peer.ssl);
1682             shutdown(snew, SHUT_RDWR);
1683             close(snew);
1684             client->peer.ssl = NULL;
1685             continue;
1686         }
1687         pthread_detach(tlsserverth);
1688     }
1689     return 0;
1690 }
1691
1692 void addrealm(char *value, char *server) {
1693     int i;
1694     struct realm *realm;
1695     
1696     for (i = 0; i < server_count; i++)
1697         if (!strcasecmp(server, servers[i].peer.host))
1698             break;
1699     if (i == server_count)
1700         debugx(1, DBG_ERR, "addrealm failed, no server %s", server);
1701
1702     /* temporary warnings */
1703     if (*value == '*')
1704         debugx(1, DBG_ERR, "Regexps are now used for specifying realms, a string\nstarting with '*' is meaningless, you probably want '.*' for matching everything\nEXITING\n");
1705     if (value[strlen(value) - 1] != '$' && value[strlen(value) - 1] != '*') {
1706         debug(DBG_ERR, "Regexps are now used for specifying realms, you\nprobably want to rewrite this as e.g. '@example\\.com$' or '\\.com$'\nYou can even do things like '^[a-n].*@example\\.com$' to make about half of the\nusers use this server. Note that the matching is case insensitive.\n");
1707         sleep(3);
1708     }
1709     realm_count++;
1710     realms = realloc(realms, realm_count * sizeof(struct realm));
1711     if (!realms)
1712         debugx(1, DBG_ERR, "malloc failed");
1713     realm = realms + realm_count - 1;
1714     memset(realm, 0, sizeof(struct realm));
1715     realm->name = stringcopy(value, 0);
1716     realm->server = servers + i;
1717     if (regcomp(&realm->regex, value, REG_ICASE | REG_NOSUB))
1718         debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", value);
1719     debug(DBG_DBG, "addrealm: added realm %s for server %s", value, server);
1720 }
1721
1722 char *parsehostport(char *s, struct peer *peer) {
1723     char *p, *field;
1724     int ipv6 = 0;
1725
1726     p = s;
1727     /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
1728     if (*p == '[') {
1729         p++;
1730         field = p;
1731         for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1732         if (*p != ']')
1733             debugx(1, DBG_ERR, "no ] matching initial [");
1734         ipv6 = 1;
1735     } else {
1736         field = p;
1737         for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1738     }
1739     if (field == p)
1740         debugx(1, DBG_ERR, "missing host/address");
1741
1742     peer->host = stringcopy(field, p - field);
1743     if (ipv6) {
1744         p++;
1745         if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
1746             debugx(1, DBG_ERR, "unexpected character after ]");
1747     }
1748     if (*p == ':') {
1749             /* port number or service name is specified */;
1750             field = ++p;
1751             for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1752             if (field == p)
1753                 debugx(1, DBG_ERR, "syntax error, : but no following port");
1754             peer->port = stringcopy(field, p - field);
1755     } else
1756         peer->port = stringcopy(peer->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT, 0);
1757     return p;
1758 }
1759
1760 /* TODO remove this */
1761 /* * is default, else longest match ... ";" used for separator */
1762 char *parserealmlist(char *s, struct server *server) {
1763 #if 0    
1764     char *p;
1765     int i, n, l;
1766     char *realmdata;
1767     char **realms;
1768
1769     for (p = s, n = 1; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++)
1770         if (*p == ';')
1771             n++;
1772     l = p - s;
1773     if (!l)
1774         debugx(1, DBG_ERR, "realm list must be specified");
1775
1776     realmdata = stringcopy(s, l);
1777     realms = malloc((1+n) * sizeof(char *));
1778     if (!realms)
1779         debugx(1, DBG_ERR, "malloc failed");
1780     realms[0] = realmdata;
1781     for (n = 1, i = 0; i < l; i++)
1782         if (realmdata[i] == ';') {
1783             realmdata[i] = '\0';
1784             realms[n++] = realmdata + i + 1;
1785         }       
1786     for (i = 0; i < n; i++)
1787         addrealm(realms[i], server->peer.host);
1788     free(realms);
1789     free(realmdata);
1790     return p;
1791 #else
1792     char *start;
1793     char *realm;
1794
1795     for (start = s;; s++)
1796         if (!*s || *s == ';' || *s == ' ' || *s == '\t' || *s == '\n') {
1797             if (s - start > 0) {
1798                 realm = stringcopy(start, s - start);
1799                 addrealm(realm, server->peer.host);
1800                 free(realm);
1801             }
1802             if (*s != ';')
1803                 return s;
1804             start = s + 1;
1805         }
1806 #endif    
1807 }
1808
1809 FILE *openconfigfile(const char *filename) {
1810     FILE *f;
1811     char pathname[100], *base;
1812     
1813     f = fopen(filename, "r");
1814     if (f) {
1815         debug(DBG_DBG, "reading config file %s", filename);
1816         return f;
1817     }
1818
1819     if (strlen(filename) + 1 <= sizeof(pathname)) {
1820         /* basename() might modify the string */
1821         strcpy(pathname, filename);
1822         base = basename(pathname);
1823         f = fopen(base, "r");
1824     }
1825
1826     if (!f)
1827         debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
1828     
1829     debug(DBG_DBG, "reading config file %s", base);
1830     return f;
1831 }
1832
1833 /* exactly one argument must be non-NULL */
1834 void getconfig(const char *serverfile, const char *clientfile) {
1835     FILE *f;
1836     char line[1024];
1837     char *p, *field;
1838     struct client *client;
1839     struct server *server;
1840     struct peer *peer;
1841     int i, count, *ucount, *tcount;
1842  
1843     f = openconfigfile(serverfile ? serverfile : clientfile);
1844     if (serverfile) {
1845         ucount = &server_udp_count;
1846         tcount = &server_tls_count;
1847     } else {
1848         ucount = &client_udp_count;
1849         tcount = &client_tls_count;
1850     }
1851     while (fgets(line, 1024, f)) {
1852         for (p = line; *p == ' ' || *p == '\t'; p++);
1853         switch (*p) {
1854         case '#':
1855         case '\n':
1856             break;
1857         case 'T':
1858             (*tcount)++;
1859             break;
1860         case 'U':
1861             (*ucount)++;
1862             break;
1863         default:
1864             debugx(1, DBG_ERR, "type must be U or T, got %c", *p);
1865         }
1866     }
1867
1868     if (serverfile) {
1869         count = server_count = server_udp_count + server_tls_count;
1870         servers = calloc(count, sizeof(struct server));
1871         if (!servers)
1872             debugx(1, DBG_ERR, "malloc failed");
1873     } else {
1874         if (client_udp_count) {
1875             udp_server_replyq.replies = malloc(client_udp_count * MAX_REQUESTS * sizeof(struct reply));
1876             if (!udp_server_replyq.replies)
1877                 debugx(1, DBG_ERR, "malloc failed");
1878             udp_server_replyq.size = client_udp_count * MAX_REQUESTS;
1879             udp_server_replyq.count = 0;
1880             pthread_mutex_init(&udp_server_replyq.count_mutex, NULL);
1881             pthread_cond_init(&udp_server_replyq.count_cond, NULL);
1882         }    
1883
1884         count = client_count = client_udp_count + client_tls_count;
1885         clients = calloc(count, sizeof(struct client));
1886         if (!clients)
1887             debugx(1, DBG_ERR, "malloc failed");
1888     }
1889     
1890     rewind(f);
1891     for (i = 0; i < count && fgets(line, 1024, f);) {
1892         if (serverfile) {
1893             server = &servers[i];
1894             peer = &server->peer;
1895         } else {
1896             client = &clients[i];
1897             peer = &client->peer;
1898         }
1899         for (p = line; *p == ' ' || *p == '\t'; p++);
1900         if (*p == '#' || *p == '\n')
1901             continue;
1902         peer->type = *p;        /* we already know it must be U or T */
1903         for (p++; *p == ' ' || *p == '\t'; p++);
1904         p = parsehostport(p, peer);
1905         for (; *p == ' ' || *p == '\t'; p++);
1906         if (serverfile) {
1907             p = parserealmlist(p, server);
1908             for (; *p == ' ' || *p == '\t'; p++);
1909         }
1910         field = p;
1911         for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1912         if (field == p) {
1913             /* no secret set and end of line, line is complete if TLS */
1914             if (peer->type == 'U')
1915                 debugx(1, DBG_ERR, "secret must be specified for UDP");
1916             peer->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
1917         } else {
1918             peer->secret = stringcopy(field, p - field);
1919             /* check that rest of line only white space */
1920             for (; *p == ' ' || *p == '\t'; p++);
1921             if (*p && *p != '\n')
1922                 debugx(1, DBG_ERR, "max 4 fields per line, found a 5th");
1923         }
1924
1925         if ((serverfile && !resolvepeer(&server->peer, 0)) ||
1926             (clientfile && !resolvepeer(&client->peer, 0)))
1927             debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", peer->host, peer->port);
1928
1929         if (serverfile) {
1930             pthread_mutex_init(&server->lock, NULL);
1931             server->sock = -1;
1932             server->requests = calloc(MAX_REQUESTS, sizeof(struct request));
1933             if (!server->requests)
1934                 debugx(1, DBG_ERR, "malloc failed");
1935             server->newrq = 0;
1936             pthread_mutex_init(&server->newrq_mutex, NULL);
1937             pthread_cond_init(&server->newrq_cond, NULL);
1938         } else {
1939             if (peer->type == 'U')
1940                 client->replyq = &udp_server_replyq;
1941             else {
1942                 client->replyq = malloc(sizeof(struct replyq));
1943                 if (!client->replyq)
1944                     debugx(1, DBG_ERR, "malloc failed");
1945                 client->replyq->replies = calloc(MAX_REQUESTS, sizeof(struct reply));
1946                 if (!client->replyq->replies)
1947                     debugx(1, DBG_ERR, "malloc failed");
1948                 client->replyq->size = MAX_REQUESTS;
1949                 client->replyq->count = 0;
1950                 pthread_mutex_init(&client->replyq->count_mutex, NULL);
1951                 pthread_cond_init(&client->replyq->count_cond, NULL);
1952             }
1953         }
1954         debug(DBG_DBG, "got type %c, host %s, port %s, secret %s", peer->type, peer->host, peer->port, peer->secret);
1955         i++;
1956     }
1957     fclose(f);
1958 }
1959
1960 struct peer *server_create(char type) {
1961     struct peer *server;
1962     char *conf;
1963
1964     server = malloc(sizeof(struct peer));
1965     if (!server)
1966         debugx(1, DBG_ERR, "malloc failed");
1967     memset(server, 0, sizeof(struct peer));
1968     server->type = type;
1969     conf = (type == 'T' ? options.listentcp : options.listenudp);
1970     if (conf) {
1971         parsehostport(conf, server);
1972         if (!strcmp(server->host, "*")) {
1973             free(server->host);
1974             server->host = NULL;
1975         }
1976     } else
1977         server->port = stringcopy(type == 'T' ? DEFAULT_TLS_PORT : DEFAULT_UDP_PORT, 0);
1978     if (!resolvepeer(server, AI_PASSIVE))
1979         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", server->host, server->port);
1980     return server;
1981 }
1982
1983 /* Parses config with following syntax:
1984  * One of these:
1985  * option-name value
1986  * option-name = value
1987  * Or:
1988  * option-name value {
1989  *     option-name [=] value
1990  *     ...
1991  * }
1992  */
1993 void getgeneralconfig(FILE *f, char *block, ...) {
1994     va_list ap;
1995     char line[1024];
1996     char *tokens[3], *opt, *val, *word, **str;
1997     int type, tcount, conftype;
1998     void (*cbk)(FILE *, char *, char *);
1999         
2000     while (fgets(line, 1024, f)) {
2001         tokens[0] = strtok(line, " \t\n");
2002         if (!*tokens || **tokens == '#')
2003             continue;
2004         for (tcount = 1; tcount < 3 && (tokens[tcount] = strtok(NULL, " \t\n")); tcount++);
2005         
2006         if (tcount && **tokens == '}') {
2007             if (block)
2008                 return;
2009             debugx(1, DBG_ERR, "configuration error, found } with no matching {");
2010         }
2011             
2012         switch (tcount) {
2013         case 2:
2014             opt = tokens[0];
2015             val = tokens[1];
2016             conftype = CONF_STR;
2017             break;
2018         case 3:
2019             if (tokens[1][0] == '=' && tokens[1][1] == '\0') {
2020                 opt = tokens[0];
2021                 val = tokens[2];
2022                 conftype = CONF_STR;
2023                 break;
2024             }
2025             if (tokens[2][0] == '{' && tokens[2][1] == '\0') {
2026                 opt = tokens[0];
2027                 val = tokens[1];
2028                 conftype = CONF_CBK;
2029                 break;
2030             }
2031             /* fall through */
2032         default:
2033             if (block)
2034                 debugx(1, DBG_ERR, "configuration error in block %s, line starting with %s", block, tokens[0]);
2035             debugx(1, DBG_ERR, "configuration error, syntax error in line starting with %s", tokens[0]);
2036         }
2037
2038         va_start(ap, block);
2039         while ((word = va_arg(ap, char *))) {
2040             type = va_arg(ap, int);
2041             switch (type) {
2042             case CONF_STR:
2043                 str = va_arg(ap, char **);
2044                 if (!str)
2045                     debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2046                 break;
2047             case CONF_CBK:
2048                 cbk = va_arg(ap, void (*)(FILE *, char *, char *));
2049                 break;
2050             default:
2051                 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2052             }
2053             if (!strcasecmp(opt, word))
2054                 break;
2055         }
2056         va_end(ap);
2057         
2058         if (!word) {
2059             if (block)
2060                 debugx(1, DBG_ERR, "configuration error in block %s, unknown option %s", block, opt);
2061             debugx(1, DBG_ERR, "configuration error, unknown option %s", opt);
2062         }
2063
2064         if (type != conftype) {
2065             if (block)
2066                 debugx(1, DBG_ERR, "configuration error in block %s, wrong syntax for option %s", block, opt);
2067             debugx(1, DBG_ERR, "configuration error, wrong syntax for option %s", opt);
2068         }
2069         
2070         switch (type) {
2071         case CONF_STR:
2072             if (block)
2073                 debug(DBG_DBG, "getgeneralconfig: block %s: %s = %s", block, opt, val);
2074             else 
2075                 debug(DBG_DBG, "getgeneralconfig: %s = %s", opt, val);
2076             *str = stringcopy(val, 0);
2077             break;
2078         case CONF_CBK:
2079             cbk(f, opt, val);
2080             break;
2081         default:
2082             debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2083         }
2084     }
2085 }
2086
2087 void confclsrv_cb(FILE *f, char *opt, char *val) {
2088     char *type = NULL, *secret = NULL, *port = NULL, *statusserver = NULL;
2089     char *block;
2090     struct client *client = NULL;
2091     struct server *server = NULL;
2092     struct peer *peer;
2093
2094     block = malloc(strlen(opt) + strlen(val) + 2);
2095     if (!block)
2096         debugx(1, DBG_ERR, "malloc failed");
2097     sprintf(block, "%s %s", opt, val);
2098     debug(DBG_DBG, "confclsrv_cb called for %s", block);
2099     
2100     if (!strcasecmp(opt, "client")) {
2101         getgeneralconfig(f, block,
2102                          "type", CONF_STR, &type,
2103                          "secret", CONF_STR, &secret,
2104                          NULL
2105                          );
2106         client_count++;
2107         clients = realloc(clients, client_count * sizeof(struct client));
2108         if (!clients)
2109             debugx(1, DBG_ERR, "malloc failed");
2110         client = clients + client_count - 1;
2111         memset(client, 0, sizeof(struct client));
2112         peer = &client->peer;
2113     } else {
2114         getgeneralconfig(f, block,
2115                          "type", CONF_STR, &type,
2116                          "secret", CONF_STR, &secret,
2117                          "port", CONF_STR, &port,
2118                          "StatusServer", CONF_STR, &statusserver,
2119                          NULL
2120                          );
2121         server_count++;
2122         servers = realloc(servers, server_count * sizeof(struct server));
2123         if (!servers)
2124             debugx(1, DBG_ERR, "malloc failed");
2125         server = servers + server_count - 1;
2126         memset(server, 0, sizeof(struct server));
2127         peer = &server->peer;
2128         peer->port = port;
2129         if (statusserver) {
2130             if (!strcasecmp(statusserver, "on"))
2131                 server->statusserver = 1;
2132             else if (strcasecmp(statusserver, "off"))
2133                 debugx(1, DBG_ERR, "error in block %s, StatusServer is %s, must be on or off", block, statusserver);
2134             free(statusserver);
2135         }
2136     }
2137     
2138     peer->host = stringcopy(val, 0);
2139     
2140     if (type && !strcasecmp(type, "udp")) {
2141         peer->type = 'U';
2142         if (client)
2143             client_udp_count++;
2144         else {
2145             server_udp_count++;
2146             if (!port)
2147                 peer->port = stringcopy(DEFAULT_UDP_PORT, 0);
2148         }
2149     } else if (type && !strcasecmp(type, "tls")) {
2150         peer->type = 'T';
2151         if (client)
2152             client_tls_count++;
2153         else {
2154             server_tls_count++;
2155             if (!port)
2156                 peer->port = stringcopy(DEFAULT_TLS_PORT, 0);
2157         }
2158     } else
2159         debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2160     free(type);
2161     
2162     if (!resolvepeer(peer, 0))
2163         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", peer->host, peer->port);
2164     
2165     if (!secret) {
2166         if (peer->type == 'U')
2167             debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2168         peer->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2169     } else {
2170         peer->secret = secret;
2171     }
2172
2173     if (client) {
2174         if (peer->type == 'U')
2175             client->replyq = &udp_server_replyq;
2176         else {
2177             client->replyq = malloc(sizeof(struct replyq));
2178             if (!client->replyq)
2179                 debugx(1, DBG_ERR, "malloc failed");
2180             client->replyq->replies = calloc(MAX_REQUESTS, sizeof(struct reply));
2181             if (!client->replyq->replies)
2182                 debugx(1, DBG_ERR, "malloc failed");
2183             client->replyq->size = MAX_REQUESTS;
2184             client->replyq->count = 0;
2185             pthread_mutex_init(&client->replyq->count_mutex, NULL);
2186             pthread_cond_init(&client->replyq->count_cond, NULL);
2187         }
2188     } else {
2189         pthread_mutex_init(&server->lock, NULL);
2190         server->sock = -1;
2191         server->requests = calloc(MAX_REQUESTS, sizeof(struct request));
2192         if (!server->requests)
2193             debugx(1, DBG_ERR, "malloc failed");
2194         server->newrq = 0;
2195         pthread_mutex_init(&server->newrq_mutex, NULL);
2196         pthread_cond_init(&server->newrq_cond, NULL);
2197     }
2198     
2199     free(block);
2200 }
2201
2202 void confrealm_cb(FILE *f, char *opt, char *val) {
2203     char *server = NULL;
2204     char *block;
2205     
2206     block = malloc(strlen(opt) + strlen(val) + 2);
2207     if (!block)
2208         debugx(1, DBG_ERR, "malloc failed");
2209     sprintf(block, "%s %s", opt, val);
2210     debug(DBG_DBG, "confrealm_cb called for %s", block);
2211     
2212     getgeneralconfig(f, block,
2213                      "server", CONF_STR, &server,
2214                      NULL
2215                      );
2216     if (!server)
2217         debugx(1, DBG_ERR, "error in block %s, server must be specified", block);
2218
2219     addrealm(val, server);
2220     free(server);
2221     free(block);
2222 }
2223
2224 void getmainconfig(const char *configfile) {
2225     FILE *f;
2226     char *loglevel = NULL;
2227
2228     f = openconfigfile(configfile);
2229     memset(&options, 0, sizeof(options));
2230
2231     getgeneralconfig(f, NULL,
2232                      "TLSCACertificateFile", CONF_STR, &options.tlscacertificatefile,
2233                      "TLSCACertificatePath", CONF_STR, &options.tlscacertificatepath,
2234                      "TLSCertificateFile", CONF_STR, &options.tlscertificatefile,
2235                      "TLSCertificateKeyFile", CONF_STR, &options.tlscertificatekeyfile,
2236                      "TLSCertificateKeyPassword", CONF_STR, &options.tlscertificatekeypassword,
2237                      "ListenUDP", CONF_STR, &options.listenudp,
2238                      "ListenTCP", CONF_STR, &options.listentcp,
2239                      "LogLevel", CONF_STR, &loglevel,
2240                      "LogDestination", CONF_STR, &options.logdestination,
2241                      "Client", CONF_CBK, confclsrv_cb,
2242                      "Server", CONF_CBK, confclsrv_cb,
2243                      "Realm", CONF_CBK, confrealm_cb,
2244                      NULL
2245                      );
2246     fclose(f);
2247
2248     if (loglevel) {
2249         if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
2250             debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
2251         options.loglevel = *loglevel - '0';
2252         free(loglevel);
2253     }
2254
2255     if (client_udp_count) {
2256         udp_server_replyq.replies = malloc(client_udp_count * MAX_REQUESTS * sizeof(struct reply));
2257         if (!udp_server_replyq.replies)
2258             debugx(1, DBG_ERR, "malloc failed");
2259         udp_server_replyq.size = client_udp_count * MAX_REQUESTS;
2260         udp_server_replyq.count = 0;
2261         pthread_mutex_init(&udp_server_replyq.count_mutex, NULL);
2262         pthread_cond_init(&udp_server_replyq.count_cond, NULL);
2263     }    
2264 }
2265
2266 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *loglevel, char **configfile) {
2267     int c;
2268
2269     while ((c = getopt(argc, argv, "c:d:fv")) != -1) {
2270         switch (c) {
2271         case 'c':
2272             *configfile = optarg;
2273             break;
2274         case 'd':
2275             if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
2276                 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
2277             *loglevel = *optarg - '0';
2278             break;
2279         case 'f':
2280             *foreground = 1;
2281             break;
2282         case 'v':
2283                 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
2284         default:
2285             goto usage;
2286         }
2287     }
2288     if (!(argc - optind))
2289         return;
2290
2291  usage:
2292     debug(DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -v ]", argv[0]);
2293     exit(1);
2294 }
2295
2296 int main(int argc, char **argv) {
2297     pthread_t udpserverth;
2298     int i;
2299     uint8_t foreground = 0, loglevel = 0;
2300     char *configfile = NULL;
2301     
2302     debug_init("radsecproxy");
2303     debug_set_level(DEBUG_LEVEL);
2304     getargs(argc, argv, &foreground, &loglevel, &configfile);
2305     if (loglevel)
2306         debug_set_level(loglevel);
2307     getmainconfig(configfile ? configfile : CONFIG_MAIN);
2308     if (loglevel)
2309         options.loglevel = loglevel;
2310     else if (options.loglevel)
2311         debug_set_level(options.loglevel);
2312     if (foreground)
2313         options.logdestination = NULL;
2314     else {
2315         if (!options.logdestination)
2316             options.logdestination = "x-syslog://";
2317         debug_set_destination(options.logdestination);
2318     }
2319
2320     /* TODO remove getconfig completely when all use new config method */
2321     if (!server_count)
2322         getconfig(CONFIG_SERVERS, NULL);
2323     if (!client_count)
2324         getconfig(NULL, CONFIG_CLIENTS);
2325
2326     /* TODO exit if not at least one client and one server configured */
2327     if (!realm_count)
2328         debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
2329
2330     if (!foreground && (daemon(0, 0) < 0))
2331         debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
2332         
2333     if (client_udp_count) {
2334         udp_server_listen = server_create('U');
2335         if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
2336             debugx(1, DBG_ERR, "pthread_create failed");
2337     }
2338     
2339     if (client_tls_count || server_tls_count)
2340         ssl_ctx = ssl_init();
2341     
2342     for (i = 0; i < server_count; i++)
2343         if (pthread_create(&servers[i].clientth, NULL, clientwr, (void *)&servers[i]))
2344             debugx(1, DBG_ERR, "pthread_create failed");
2345
2346     if (client_tls_count) {
2347         tcp_server_listen = server_create('T');
2348         return tlslistener();
2349     }
2350     
2351     /* just hang around doing nothing, anything to do here? */
2352     for (;;)
2353         sleep(1000);
2354 }