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