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