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