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