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