tlsconnect changes
[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 /* BUGS:
10  * peers can not yet be specified with literal IPv6 addresses due to port syntax
11  */
12
13 /* TODO:
14  * Among other things:
15  * timer based client retrans or maybe no retrans and just a timer...
16  * make our server ignore client retrans?
17  * tls keep alives
18  * routing based on id....
19  * need to also encrypt Tunnel-Password and Message-Authenticator attrs
20  * tls certificate validation
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 "radsecproxy.h"
55
56 static struct peer peers[MAX_PEERS];
57 static int peer_count = 0;
58
59 static struct replyq udp_server_replyq;
60 static int udp_server_sock = -1;
61 static char *udp_server_port = DEFAULT_UDP_PORT;
62 static pthread_mutex_t *ssl_locks;
63 static long *ssl_lock_count;
64 static SSL_CTX *ssl_ctx_cl;
65 extern int optind;
66 extern char *optarg;
67
68 /* callbacks for making OpenSSL thread safe */
69 unsigned long ssl_thread_id() {
70         return (unsigned long)pthread_self();
71 };
72
73 void ssl_locking_callback(int mode, int type, const char *file, int line) {
74     if (mode & CRYPTO_LOCK) {
75         pthread_mutex_lock(&ssl_locks[type]);
76         ssl_lock_count[type]++;
77     } else
78         pthread_mutex_unlock(&ssl_locks[type]);
79 }
80
81 void ssl_locks_setup() {
82     int i;
83
84     ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
85     ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
86     for (i = 0; i < CRYPTO_num_locks(); i++) {
87         ssl_lock_count[i] = 0;
88         pthread_mutex_init(&ssl_locks[i], NULL);
89     }
90
91     CRYPTO_set_id_callback(ssl_thread_id);
92     CRYPTO_set_locking_callback(ssl_locking_callback);
93 }
94
95 int resolvepeer(struct peer *peer) {
96     struct addrinfo hints;
97     
98     pthread_mutex_lock(&peer->lock);
99     if (peer->addrinfo) {
100         /* assume we should re-resolve */
101         freeaddrinfo(peer->addrinfo);
102         peer->addrinfo = NULL;
103     }
104     
105     memset(&hints, 0, sizeof(hints));
106     hints.ai_socktype = (peer->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
107     hints.ai_family = AF_UNSPEC;
108     if (getaddrinfo(peer->host, peer->port, &hints, &peer->addrinfo)) {
109         err("resolvepeer: can't resolve %s port %s", peer->host, peer->port);
110         peer->addrinfo = NULL; /* probably don't need this */
111         pthread_mutex_unlock(&peer->lock);
112         return 0;
113     }
114     pthread_mutex_unlock(&peer->lock);
115     return 1;
116 }         
117
118 int connecttopeer(struct peer *peer) {
119     int s;
120     struct addrinfo *res;
121     
122     if (!peer->addrinfo) {
123         resolvepeer(peer);
124         if (!peer->addrinfo) {
125             printf("connecttopeer: can't resolve %s into address to connect to\n", peer->host);
126             return -1;
127         }
128     }
129
130     for (res = peer->addrinfo; res; res = res->ai_next) {
131         s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
132         if (s < 0) {
133             err("connecttopeer: socket failed");
134             continue;
135         }
136         if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
137             break;
138         err("connecttopeer: connect failed");
139         close(s);
140         s = -1;
141     }
142     return s;
143 }         
144
145 /* returns the peer with matching address, or NULL */
146 /* if peer argument is not NULL, we only check that one peer */
147 struct peer *find_peer(char type, struct sockaddr *addr, struct peer *peer) {
148     struct sockaddr_in6 *sa6;
149     struct in_addr *a4 = NULL;
150     struct peer *p;
151     int i;
152     struct addrinfo *res;
153
154     if (addr->sa_family == AF_INET6) {
155         sa6 = (struct sockaddr_in6 *)addr;
156         if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
157             a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
158     } else
159         a4 = &((struct sockaddr_in *)addr)->sin_addr;
160
161     p = (peer ? peer : peers);
162     for (i = 0; i < peer_count; i++) {
163         if (p->type == type)
164             for (res = p->addrinfo; res; res = res->ai_next)
165                 if ((a4 && res->ai_family == AF_INET &&
166                      !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
167                     (res->ai_family == AF_INET6 &&
168                      !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
169                     return p;
170         if (peer)
171             break;
172         p++;
173     }
174     return NULL;
175 }
176
177 /* if *peer == NULL we return who we received from, else require it to be from peer */
178 /* return from in sa if not NULL */
179 unsigned char *radudpget(int s, struct peer **peer, struct sockaddr_storage *sa) {
180     int cnt, len;
181     struct peer *f;
182     unsigned char buf[65536], *rad;
183     struct sockaddr_storage from;
184     socklen_t fromlen = sizeof(from);
185
186     for (;;) {
187         cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
188         if (cnt == -1) {
189             err("radudpget: recv failed");
190             continue;
191         }
192         printf("radudpget: got %d bytes from %s\n", cnt, addr2string((struct sockaddr *)&from, fromlen));
193
194         if (cnt < 20) {
195             printf("radudpget: packet too small\n");
196             continue;
197         }
198     
199         len = RADLEN(buf);
200
201         if (cnt < len) {
202             printf("radudpget: packet smaller than length field in radius header\n");
203             continue;
204         }
205         if (cnt > len)
206             printf("radudpget: packet was padded with %d bytes\n", cnt - len);
207
208         f = find_peer('U', (struct sockaddr *)&from, *peer);
209         if (!f) {
210             printf("radudpget: got packet from wrong or unknown UDP peer, ignoring\n");
211             continue;
212         }
213
214         rad = malloc(len);
215         if (rad)
216             break;
217         err("radudpget: malloc failed");
218     }
219     memcpy(rad, buf, len);
220     *peer = f; /* only need this if *peer == NULL, but if not NULL *peer == f here */
221     if (sa)
222         *sa = from;
223     return rad;
224 }
225
226 void tlsconnect(struct peer *peer, struct timeval *when, char *text) {
227     struct timeval now;
228     time_t elapsed;
229     unsigned long error;
230
231     pthread_mutex_lock(&peer->lock);
232     if (when && memcmp(&peer->lastconnecttry, when, sizeof(struct timeval))) {
233         /* already reconnected, nothing to do */
234         printf("tlsconnect: seems already reconnected\n");
235         pthread_mutex_unlock(&peer->lock);
236         return;
237     }
238
239     printf("tlsconnect %s\n", text);
240
241     for (;;) {
242         printf("tlsconnect: trying to open TLS connection to %s port %s\n", peer->host, peer->port);
243         gettimeofday(&now, NULL);
244         elapsed = now.tv_sec - peer->lastconnecttry.tv_sec;
245         if (peer->connectionok) {
246             peer->connectionok = 0;
247             sleep(10);
248         } else if (elapsed < 5)
249             sleep(10);
250         else if (elapsed < 600)
251             sleep(elapsed * 2);
252         else if (elapsed < 10000) /* no sleep at startup */
253                 sleep(900);
254         if (peer->sockcl >= 0)
255             close(peer->sockcl);
256         if ((peer->sockcl = connecttopeer(peer)) < 0)
257             continue;
258         SSL_free(peer->sslcl);
259         peer->sslcl = SSL_new(ssl_ctx_cl);
260         SSL_set_fd(peer->sslcl, peer->sockcl);
261         if (SSL_connect(peer->sslcl) > 0)
262             break;
263         while ((error = ERR_get_error()))
264             err("tlsconnect: TLS: %s", ERR_error_string(error, NULL));
265     }
266     printf("tlsconnect: TLS connection to %s port %s up\n", peer->host, peer->port);
267     pthread_mutex_unlock(&peer->lock);
268 }
269
270 unsigned char *radtlsget(SSL *ssl) {
271     int cnt, total, len;
272     unsigned char buf[4], *rad;
273
274     for (;;) {
275         for (total = 0; total < 4; total += cnt) {
276             cnt = SSL_read(ssl, buf + total, 4 - total);
277             if (cnt <= 0) {
278                 printf("radtlsget: connection lost\n");
279                 return NULL;
280             }
281         }
282
283         len = RADLEN(buf);
284         rad = malloc(len);
285         if (!rad) {
286             err("radtlsget: malloc failed");
287             continue;
288         }
289         memcpy(rad, buf, 4);
290
291         for (; total < len; total += cnt) {
292             cnt = SSL_read(ssl, rad + total, len - total);
293             if (cnt <= 0) {
294                 printf("radtlsget: connection lost\n");
295                 free(rad);
296                 return NULL;
297             }
298         }
299     
300         if (total >= 20)
301             break;
302         
303         free(rad);
304         printf("radtlsget: packet smaller than minimum radius size\n");
305     }
306     
307     printf("radtlsget: got %d bytes\n", total);
308     return rad;
309 }
310
311 int clientradput(struct peer *peer, unsigned char *rad) {
312     int cnt;
313     size_t len;
314     unsigned long error;
315     struct timeval lastconnecttry;
316     
317     len = RADLEN(rad);
318     if (peer->type == 'U') {
319         if (send(peer->sockcl, rad, len, 0) >= 0) {
320             printf("clienradput: sent UDP of length %d to %s port %s\n", len, peer->host, peer->port);
321             return 1;
322         }
323         err("clientradput: send failed");
324         return 0;
325     }
326
327     lastconnecttry = peer->lastconnecttry;
328     while ((cnt = SSL_write(peer->sslcl, rad, len)) <= 0) {
329         while ((error = ERR_get_error()))
330             err("clientwr: TLS: %s", ERR_error_string(error, NULL));
331         tlsconnect(peer, &lastconnecttry, "clientradput");
332         lastconnecttry = peer->lastconnecttry;
333     }
334
335     peer->connectionok = 1;
336     printf("clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s\n",
337            cnt, len, peer->host);
338     return 1;
339 }
340
341 int radsign(unsigned char *rad, unsigned char *sec) {
342     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
343     static unsigned char first = 1;
344     static EVP_MD_CTX mdctx;
345     unsigned int md_len;
346     int result;
347     
348     pthread_mutex_lock(&lock);
349     if (first) {
350         EVP_MD_CTX_init(&mdctx);
351         first = 0;
352     }
353
354     result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
355         EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
356         EVP_DigestUpdate(&mdctx, sec, strlen(sec)) &&
357         EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
358         md_len == 16);
359     pthread_mutex_unlock(&lock);
360     return result;
361 }
362
363 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
364     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
365     static unsigned char first = 1;
366     static EVP_MD_CTX mdctx;
367     unsigned char hash[EVP_MAX_MD_SIZE];
368     unsigned int len;
369     int result;
370     
371     pthread_mutex_lock(&lock);
372     if (first) {
373         EVP_MD_CTX_init(&mdctx);
374         first = 0;
375     }
376
377     len = RADLEN(rad);
378     
379     result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
380               EVP_DigestUpdate(&mdctx, rad, 4) &&
381               EVP_DigestUpdate(&mdctx, reqauth, 16) &&
382               (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
383               EVP_DigestUpdate(&mdctx, sec, strlen(sec)) &&
384               EVP_DigestFinal_ex(&mdctx, hash, &len) &&
385               len == 16 &&
386               !memcmp(hash, rad + 4, 16));
387     pthread_mutex_unlock(&lock);
388     return result;
389 }
390               
391 void sendrq(struct peer *to, struct peer *from, struct request *rq) {
392     int i;
393
394     pthread_mutex_lock(&to->newrq_mutex);
395     for (i = 0; i < MAX_REQUESTS; i++)
396         if (!to->requests[i].buf)
397             break;
398     if (i == MAX_REQUESTS) {
399         printf("No room in queue, dropping request\n");
400         pthread_mutex_unlock(&to->newrq_mutex);
401         return;
402     }
403     
404     rq->buf[1] = (char)i;
405     to->requests[i] = *rq;
406
407     if (!to->newrq) {
408         to->newrq = 1;
409         printf("signalling client writer\n");
410         pthread_cond_signal(&to->newrq_cond);
411     }
412     pthread_mutex_unlock(&to->newrq_mutex);
413 }
414
415 void sendreply(struct peer *to, struct peer *from, char *buf, struct sockaddr_storage *tosa) {
416     struct replyq *replyq = to->replyq;
417     
418     pthread_mutex_lock(&replyq->count_mutex);
419     if (replyq->count == replyq->size) {
420         printf("No room in queue, dropping request\n");
421         pthread_mutex_unlock(&replyq->count_mutex);
422         return;
423     }
424
425     replyq->replies[replyq->count].buf = buf;
426     if (tosa)
427         replyq->replies[replyq->count].tosa = *tosa;
428     replyq->count++;
429
430     if (replyq->count == 1) {
431         printf("signalling client writer\n");
432         pthread_cond_signal(&replyq->count_cond);
433     }
434     pthread_mutex_unlock(&replyq->count_mutex);
435 }
436
437 int pwdcrypt(uint8_t *plain, uint8_t *enc, uint8_t enclen, uint8_t *shared, uint8_t sharedlen,
438                 uint8_t *auth) {
439     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
440     static unsigned char first = 1;
441     static EVP_MD_CTX mdctx;
442     unsigned char hash[EVP_MAX_MD_SIZE], *input;
443     unsigned int md_len;
444     uint8_t i, offset = 0;
445     
446     pthread_mutex_lock(&lock);
447     if (first) {
448         EVP_MD_CTX_init(&mdctx);
449         first = 0;
450     }
451
452     input = auth;
453     for (;;) {
454         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
455             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
456             !EVP_DigestUpdate(&mdctx, input, 16) ||
457             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
458             md_len != 16) {
459             pthread_mutex_unlock(&lock);
460             return 0;
461         }
462         for (i = 0; i < 16; i++)
463             plain[offset + i] = hash[i] ^ enc[offset + i];
464         offset += 16;
465         if (offset == enclen)
466             break;
467         input = enc + offset - 16;
468     }
469     pthread_mutex_unlock(&lock);
470     return 1;
471 }
472
473 struct peer *radsrv(struct request *rq, char *buf, struct peer *from) {
474     uint8_t code, id, *auth, *attr, *usernameattr = NULL, *userpwdattr = NULL, pwd[128], pwdlen;
475     int i;
476     uint16_t len;
477     int left;
478     struct peer *to;
479     unsigned char newauth[16];
480     
481     code = *(uint8_t *)buf;
482     id = *(uint8_t *)(buf + 1);
483     len = RADLEN(buf);
484     auth = (uint8_t *)(buf + 4);
485
486     printf("radsrv: code %d, id %d, length %d\n", code, id, len);
487     
488     if (code != RAD_Access_Request) {
489         printf("radsrv: server currently accepts only access-requests, ignoring\n");
490         return NULL;
491     }
492
493     left = len - 20;
494     attr = buf + 20;
495     
496     while (left > 1) {
497         left -= attr[RAD_Attr_Length];
498         if (left < 0) {
499             printf("radsrv: attribute length exceeds packet length, ignoring packet\n");
500             return NULL;
501         }
502         switch (attr[RAD_Attr_Type]) {
503         case RAD_Attr_User_Name:
504             usernameattr = attr;
505             break;
506         case RAD_Attr_User_Password:
507             userpwdattr = attr;
508             break;
509         }
510         attr += attr[RAD_Attr_Length];
511     }
512     if (left)
513         printf("radsrv: malformed packet? remaining byte after last attribute\n");
514
515     if (usernameattr) {
516         printf("radsrv: Username: ");
517         for (i = 0; i < usernameattr[RAD_Attr_Length]; i++)
518             printf("%c", usernameattr[RAD_Attr_Value + i]);
519         printf("\n");
520     }
521
522     /* find out where to send the packet, for now we send to first connected
523        TLS peer if UDP, and first UDP peer if TLS */
524     
525     i = peer_count;
526     switch (from->type) {
527     case 'U':
528         for (i = 0; i < peer_count; i++)
529             if (peers[i].type == 'T' && peers[i].sockcl >= 0)
530                 break;
531         break;
532     case 'T':
533         for (i = 0; i < peer_count; i++)
534             if (peers[i].type == 'U')
535                 break;
536         break;
537     }
538
539     if (i == peer_count) {
540         printf("radsrv: ignoring request, don't know where to send it\n");
541         return NULL;
542     }
543
544     to = &peers[i];
545     
546     if (!RAND_bytes(newauth, 16)) {
547         printf("radsrv: failed to generate random auth\n");
548         return NULL;
549     }
550
551     if (userpwdattr) {
552         printf("radsrv: found userpwdattr of length %d\n", userpwdattr[RAD_Attr_Length]);
553         pwdlen = userpwdattr[RAD_Attr_Length] - 2;
554         if (pwdlen < 16 || pwdlen > 128 || pwdlen % 16) {
555             printf("radsrv: invalid user password length\n");
556             return NULL;
557         }
558         
559         if (!pwdcrypt(pwd, &userpwdattr[RAD_Attr_Value], pwdlen, from->secret, strlen(from->secret), auth)) {
560             printf("radsrv: cannot decrypt password\n");
561             return NULL;
562         }
563         printf("radsrv: password: ");
564         for (i = 0; i < pwdlen; i++)
565             printf("%02x ", pwd[i]);
566         printf("\n");
567         if (!pwdcrypt(&userpwdattr[RAD_Attr_Value], pwd, pwdlen, to->secret, strlen(to->secret), newauth)) {
568             printf("radsrv: cannot encrypt password\n");
569             return NULL;
570         }
571     }
572
573     rq->buf = buf;
574     rq->from = from;
575     rq->origid = id;
576     memcpy(rq->origauth, auth, 16);
577     memcpy(rq->buf + 4, newauth, 16);
578     return to;
579 }
580
581 void *clientrd(void *arg) {
582     struct peer *from, *peer = (struct peer *)arg;
583     int i;
584     unsigned char *buf;
585     struct sockaddr_storage fromsa;
586     struct timeval lastconnecttry;
587     
588     for (;;) {
589         lastconnecttry = peer->lastconnecttry;
590         buf = (peer->type == 'U' ? radudpget(peer->sockcl, &peer, NULL) : radtlsget(peer->sslcl));
591         if (!buf && peer->type == 'T') {
592             printf("retry in 60s\n");
593             sleep(60); /* should have exponential backoff perhaps, better do it inside radtlsget */
594             tlsconnect(peer, &lastconnecttry, "clientrd");
595             continue;
596         }
597
598         peer->connectionok = 1;
599         
600         i = buf[1]; /* i is the id */
601
602         pthread_mutex_lock(&peer->newrq_mutex);
603         if (!peer->requests[i].buf || !peer->requests[i].tries) {
604             pthread_mutex_unlock(&peer->newrq_mutex);
605             printf("clientrd: no matching request sent with this id, ignoring\n");
606             continue;
607         }
608         
609         if (peer->requests[i].received) {
610             pthread_mutex_unlock(&peer->newrq_mutex);
611             printf("clientrd: already received, ignoring\n");
612             continue;
613         }
614
615         if (!validauth(buf, peer->requests[i].buf + 4, peer->secret)) {
616             pthread_mutex_unlock(&peer->newrq_mutex);
617             printf("clientrd: invalid auth, ignoring\n");
618             continue;
619         }
620
621         /* once we set received = 1, requests[i] may be reused */
622         buf[1] = (char)peer->requests[i].origid;
623         memcpy(buf + 4, peer->requests[i].origauth, 16);
624         from = peer->requests[i].from;
625         if (from->type == 'U')
626             fromsa = peer->requests[i].fromsa;
627         peer->requests[i].received = 1;
628         pthread_mutex_unlock(&peer->newrq_mutex);
629
630         if (!radsign(buf, from->secret)) {
631             printf("clientrd: failed to sign message\n");
632             continue;
633         }
634         
635         printf("clientrd: giving packet back to where it came from\n");
636         sendreply(from, peer, buf, from->type == 'U' ? &fromsa : NULL);
637     }
638 }
639
640 void *clientwr(void *arg) {
641     struct peer *peer = (struct peer *)arg;
642     pthread_t clientrdth;
643     int i;
644
645     if (peer->type == 'U') {
646         if ((peer->sockcl = connecttopeer(peer)) < 0) {
647             printf("clientwr: connecttopeer failed\n");
648             exit(1);
649         }
650     } else
651         tlsconnect(peer, NULL, "new client");
652     
653     if (pthread_create(&clientrdth, NULL, clientrd, (void *)peer))
654         errx("clientwr: pthread_create failed");
655
656     for (;;) {
657         pthread_mutex_lock(&peer->newrq_mutex);
658         while (!peer->newrq) {
659             printf("clientwr: waiting for signal\n");
660             pthread_cond_wait(&peer->newrq_cond, &peer->newrq_mutex);
661             printf("clientwr: got signal\n");
662         }
663         peer->newrq = 0;
664         pthread_mutex_unlock(&peer->newrq_mutex);
665                
666         for (i = 0; i < MAX_REQUESTS; i++) {
667             pthread_mutex_lock(&peer->newrq_mutex);
668             while (!peer->requests[i].buf && i < MAX_REQUESTS)
669                 i++;
670             if (i == MAX_REQUESTS) {
671                 pthread_mutex_unlock(&peer->newrq_mutex);
672                 break;
673             }
674
675             /* already received or too many tries */
676             if (peer->requests[i].received || peer->requests[i].tries > 2) {
677                 free(peer->requests[i].buf);
678                 /* setting this to NULL means that it can be reused */
679                 peer->requests[i].buf = NULL;
680                 pthread_mutex_unlock(&peer->newrq_mutex);
681                 continue;
682             }
683             pthread_mutex_unlock(&peer->newrq_mutex);
684             
685             peer->requests[i].tries++;
686             clientradput(peer, peer->requests[i].buf);
687         }
688     }
689     /* should do more work to maintain TLS connections, keepalives etc */
690 }
691
692 void *udpserverwr(void *arg) {
693     struct replyq *replyq = &udp_server_replyq;
694     struct reply *reply = replyq->replies;
695     
696     pthread_mutex_lock(&replyq->count_mutex);
697     for (;;) {
698         while (!replyq->count) {
699             printf("udp server writer, waiting for signal\n");
700             pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
701             printf("udp server writer, got signal\n");
702         }
703         pthread_mutex_unlock(&replyq->count_mutex);
704         
705         if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
706                    (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
707             err("sendudp: send failed");
708         free(reply->buf);
709         
710         pthread_mutex_lock(&replyq->count_mutex);
711         replyq->count--;
712         memmove(replyq->replies, replyq->replies + 1,
713                 replyq->count * sizeof(struct reply));
714     }
715 }
716
717 void *udpserverrd(void *arg) {
718     struct request rq;
719     unsigned char *buf;
720     struct peer *to, *fr;
721     pthread_t udpserverwrth;
722     
723     if ((udp_server_sock = bindport(SOCK_DGRAM, udp_server_port)) < 0) {
724         printf("udpserverrd: socket/bind failed\n");
725         exit(1);
726     }
727     printf("udpserverrd: listening on UDP port %s\n", udp_server_port);
728
729     if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
730         errx("pthread_create failed");
731     
732     for (;;) {
733         fr = NULL;
734         memset(&rq, 0, sizeof(struct request));
735         buf = radudpget(udp_server_sock, &fr, &rq.fromsa);
736         to = radsrv(&rq, buf, fr);
737         if (!to) {
738             printf("udpserverrd: ignoring request, no place to send it\n");
739             continue;
740         }
741         sendrq(to, fr, &rq);
742     }
743 }
744
745 void *tlsserverwr(void *arg) {
746     int cnt;
747     unsigned long error;
748     struct peer *peer = (struct peer *)arg;
749     struct replyq *replyq;
750     
751     pthread_mutex_lock(&peer->replycount_mutex);
752     for (;;) {
753         replyq = peer->replyq;
754         while (!replyq->count) {
755             printf("tls server writer, waiting for signal\n");
756             pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
757             printf("tls server writer, got signal\n");
758         }
759         pthread_mutex_unlock(&replyq->count_mutex);
760         cnt = SSL_write(peer->sslsrv, replyq->replies->buf, RADLEN(replyq->replies->buf));
761         if (cnt > 0)
762             printf("tlsserverwr: Sent %d bytes, Radius packet of length %d\n",
763                    cnt, RADLEN(replyq->replies->buf));
764         else
765             while ((error = ERR_get_error()))
766                 err("tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
767         free(replyq->replies->buf);
768
769         pthread_mutex_lock(&replyq->count_mutex);
770         replyq->count--;
771         memmove(replyq->replies, replyq->replies + 1, replyq->count * sizeof(struct reply));
772     }
773 }
774
775 void *tlsserverrd(void *arg) {
776     struct request rq;
777     char unsigned *buf;
778     unsigned long error;
779     struct peer *to;
780     int s;
781     struct peer *peer = (struct peer *)arg;
782     pthread_t tlsserverwrth;
783
784     printf("tlsserverrd starting\n");
785     if (SSL_accept(peer->sslsrv) <= 0) {
786         while ((error = ERR_get_error()))
787             err("tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
788         errx("accept failed, child exiting");
789     }
790
791     if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)peer))
792         errx("pthread_create failed");
793     
794     for (;;) {
795         buf = radtlsget(peer->sslsrv);
796         if (!buf) {
797             printf("tlsserverrd: connection lost\n");
798             s = SSL_get_fd(peer->sslsrv);
799             SSL_free(peer->sslsrv);
800             peer->sslsrv = NULL;
801             if (s >= 0)
802                 close(s);
803             pthread_exit(NULL);
804         }
805         printf("tlsserverrd: got Radius message from %s\n", peer->host);
806         memset(&rq, 0, sizeof(struct request));
807         to = radsrv(&rq, buf, peer);
808         if (!to) {
809             printf("ignoring request, no place to send it\n");
810             continue;
811         }
812         sendrq(to, peer, &rq);
813     }
814 }
815
816 int tlslistener(SSL_CTX *ssl_ctx) {
817     pthread_t tlsserverth;
818     int s, snew;
819     struct sockaddr_storage from;
820     size_t fromlen = sizeof(from);
821     struct peer *peer;
822
823     if ((s = bindport(SOCK_STREAM, DEFAULT_TLS_PORT)) < 0) {
824         printf("tlslistener: socket/bind failed\n");
825         exit(1);
826     }
827
828     listen(s, 0);
829     printf("listening for incoming TLS on port %s\n", DEFAULT_TLS_PORT);
830
831     for (;;) {
832         snew = accept(s, (struct sockaddr *)&from, &fromlen);
833         if (snew < 0)
834             errx("accept failed");
835         printf("incoming TLS connection from %s\n", addr2string((struct sockaddr *)&from, fromlen));
836
837         peer = find_peer('T', (struct sockaddr *)&from, NULL);
838         if (!peer) {
839             printf("ignoring request, not a known TLS peer\n");
840             close(snew);
841             continue;
842         }
843
844         if (peer->sslsrv) {
845             printf("Ignoring incoming connection, already have one from this peer\n");
846             close(snew);
847             continue;
848         }
849         peer->sslsrv = SSL_new(ssl_ctx);
850         SSL_set_fd(peer->sslsrv, snew);
851         if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)peer))
852             errx("pthread_create failed");
853         
854         for (;;) {
855             /* currently only one server thread, so just halt here */
856             sleep(1000);
857         }
858     }
859     return 0;
860 }
861
862 char *parsehostport(char *s, struct peer *peer) {
863     char *p, *field;
864     int ipv6 = 0;
865
866     p = s;
867     // allow literal addresses and port, e.g. [2001:db8::1]:1812
868     if (*p == '[') {
869         p++;
870         field = p;
871         for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
872         if (*p != ']') {
873             printf("no ] matching initial [\n");
874             exit(1);
875         }
876         ipv6 = 1;
877     } else {
878         field = p;
879         for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
880     }
881     if (field == p) {
882         printf("missing host/address\n");
883         exit(1);
884     }
885     peer->host = malloc(p - field + 1);
886     if (!peer->host)
887         errx("malloc failed");
888     memcpy(peer->host, field, p - field);
889     peer->host[p - field] = '\0';
890     if (ipv6) {
891         p++;
892         if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n') {
893             printf("unexpected character after ]\n");
894             exit(1);
895         }
896     }
897     if (*p == ':') {
898             /* port number or service name is specified */;
899             field = p++;
900             for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
901             if (field == p) {
902                 printf("syntax error, : but no following port\n");
903                 exit(1);
904             }
905             peer->port = malloc(p - field + 1);
906             if (!peer->port)
907                 errx("malloc failed");
908             memcpy(peer->port, field, p - field);
909             peer->port[p - field] = '\0';
910     } else
911         peer->port = NULL;
912     return p;
913 }
914
915 // * is default, else longest match ... ";" used for separator
916 char *parserealmlist(char *s, struct peer *peer) {
917     char *p;
918     int i, n, l;
919
920     for (p = s, n = 1; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++)
921         if (*p == ';')
922             n++;
923     l = p - s;
924     if (!l) {
925         peer->realms = NULL;
926         return p;
927     }
928     peer->realmdata = malloc(l + 1);
929     if (!peer->realmdata)
930         errx("malloc failed");
931     memcpy(peer->realmdata, s, l);
932     peer->realmdata[l] = '\0';
933     peer->realms = malloc((1+n) * sizeof(char *));
934     if (!peer->realms)
935         errx("malloc failed");
936     peer->realms[0] = peer->realmdata;
937     for (n = 1, i = 0; i < l; i++)
938         if (peer->realmdata[i] == ';') {
939             peer->realmdata[i] = '\0';
940             peer->realms[n++] = peer->realmdata + i + 1;
941         }       
942     peer->realms[n] = NULL;
943     return p;
944 }
945
946 void getconfig(const char *filename) {
947     FILE *f;
948     char line[1024];
949     char *p, *field, **r;
950     struct peer *peer;
951     
952     peer_count = 0;
953     
954     udp_server_replyq.replies = malloc(4 * MAX_REQUESTS * sizeof(struct reply));
955     if (!udp_server_replyq.replies)
956         errx("malloc failed");
957     udp_server_replyq.size = 4 * MAX_REQUESTS;
958     udp_server_replyq.count = 0;
959     pthread_mutex_init(&udp_server_replyq.count_mutex, NULL);
960     pthread_cond_init(&udp_server_replyq.count_cond, NULL);
961     
962     f = fopen(filename, "r");
963     if (!f)
964         errx("getconfig failed to open %s for reading", filename);
965
966     while (fgets(line, 1024, f) && peer_count < MAX_PEERS) {
967         peer = &peers[peer_count];
968         memset(peer, 0, sizeof(struct peer));
969
970         for (p = line; *p == ' ' || *p == '\t'; p++);
971         if (*p == '#' || *p == '\n')
972             continue;
973         if (*p != 'U' && *p != 'T') {
974             printf("server type must be U or T, got %c\n", *p);
975             exit(1);
976         }
977         peer->type = *p;
978         for (p++; *p == ' ' || *p == '\t'; p++);
979         p = parsehostport(p, peer);
980         if (!peer->port)
981             peer->port = (peer->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT);
982         for (; *p == ' ' || *p == '\t'; p++);
983         p = parserealmlist(p, peer);
984         if (!peer->realms) {
985             printf("realm list must be specified\n");
986             exit(1);
987         }
988         for (; *p == ' ' || *p == '\t'; p++);
989         field = p;
990         for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
991         if (field == p) {
992             /* no secret set and end of line, line is complete if TLS */
993             if (peer->type == 'U') {
994                 printf("secret must be specified for UDP\n");
995                 exit(1);
996             }
997             peer->secret = DEFAULT_TLS_SECRET;
998         } else {
999             peer->secret = malloc(p - field + 1);
1000             if (!peer->secret)
1001                 errx("malloc failed");
1002             memcpy(peer->secret, field, p - field);
1003             peer->secret[p - field] = '\0';
1004             /* check that rest of line only white space */
1005             for (; *p == ' ' || *p == '\t'; p++);
1006             if (*p && *p != '\n') {
1007                 printf("max 4 fields per line, found a 5th\n");
1008                 exit(1);
1009             }
1010         }
1011         peer->sockcl = -1;
1012         pthread_mutex_init(&peer->lock, NULL);
1013         if (!resolvepeer(peer)) {
1014             printf("failed to resolve host %s port %s, exiting\n", peer->host, peer->port);
1015             exit(1);
1016         }
1017         peer->requests = malloc(MAX_REQUESTS * sizeof(struct request));
1018         if (!peer->requests)
1019             errx("malloc failed");
1020         memset(peer->requests, 0, MAX_REQUESTS * sizeof(struct request));
1021         peer->newrq = 0;
1022         pthread_mutex_init(&peer->newrq_mutex, NULL);
1023         pthread_cond_init(&peer->newrq_cond, NULL);
1024
1025         if (peer->type == 'U')
1026             peer->replyq = &udp_server_replyq;
1027         else {
1028             peer->replyq = malloc(sizeof(struct replyq));
1029             if (!peer->replyq)
1030                 errx("malloc failed");
1031             peer->replyq->replies = malloc(MAX_REQUESTS * sizeof(struct reply));
1032             if (!peer->replyq->replies)
1033                 errx("malloc failed");
1034             peer->replyq->size = MAX_REQUESTS;
1035             peer->replyq->count = 0;
1036             pthread_mutex_init(&peer->replyq->count_mutex, NULL);
1037             pthread_cond_init(&peer->replyq->count_cond, NULL);
1038         }
1039         printf("got type %c, host %s, port %s, secret %s\n", peers[peer_count].type,
1040                peers[peer_count].host, peers[peer_count].port, peers[peer_count].secret);
1041         printf("    with realms:");
1042         for (r = peer->realms; *r; r++)
1043             printf(" %s", *r);
1044         printf("\n");
1045         peer_count++;
1046     }
1047     fclose(f);
1048 }
1049
1050 void parseargs(int argc, char **argv) {
1051     int c;
1052
1053     while ((c = getopt(argc, argv, "p:")) != -1) {
1054         switch (c) {
1055         case 'p':
1056             udp_server_port = optarg;
1057             break;
1058         default:
1059             goto usage;
1060         }
1061     }
1062
1063     return;
1064
1065  usage:
1066     printf("radsecproxy [ -p UDP-port ]\n");
1067     exit(1);
1068 }
1069                
1070 int main(int argc, char **argv) {
1071     SSL_CTX *ssl_ctx_srv;
1072     unsigned long error;
1073     pthread_t udpserverth;
1074     pthread_attr_t joinable;
1075     int i;
1076     
1077     parseargs(argc, argv);
1078     getconfig("radsecproxy.conf");
1079     
1080     ssl_locks_setup();
1081
1082     pthread_attr_init(&joinable);
1083     pthread_attr_setdetachstate(&joinable, PTHREAD_CREATE_JOINABLE);
1084    
1085     /* listen on UDP if at least one UDP peer */
1086     
1087     for (i = 0; i < peer_count; i++)
1088         if (peers[i].type == 'U') {
1089             if (pthread_create(&udpserverth, &joinable, udpserverrd, NULL))
1090                 errx("pthread_create failed");
1091             break;
1092         }
1093     
1094     for (i = 0; i < peer_count; i++)
1095         if (peers[i].type == 'T')
1096             break;
1097
1098     if (i == peer_count) {
1099         printf("No TLS peers defined, just doing UDP proxying\n");
1100         /* just hang around doing nothing, anything to do here? */
1101         pthread_join(udpserverth, NULL);
1102         return 0;
1103     }
1104     
1105     /* SSL setup */
1106     SSL_load_error_strings();
1107     SSL_library_init();
1108
1109     while (!RAND_status()) {
1110         time_t t = time(NULL);
1111         pid_t pid = getpid();
1112         RAND_seed((unsigned char *)&t, sizeof(time_t));
1113         RAND_seed((unsigned char *)&pid, sizeof(pid));
1114     }
1115     
1116     /* initialise client part and start clients */
1117     ssl_ctx_cl = SSL_CTX_new(TLSv1_client_method());
1118     if (!ssl_ctx_cl)
1119         errx("no ssl ctx");
1120     
1121     for (i = 0; i < peer_count; i++) {
1122         if (pthread_create(&peers[i].clientth, NULL, clientwr, (void *)&peers[i]))
1123             errx("pthread_create failed");
1124     }
1125
1126     /* setting up server/daemon part */
1127     ssl_ctx_srv = SSL_CTX_new(TLSv1_server_method());
1128     if (!ssl_ctx_srv)
1129         errx("no ssl ctx");
1130     if (!SSL_CTX_use_certificate_file(ssl_ctx_srv, "/tmp/server.pem", SSL_FILETYPE_PEM)) {
1131         while ((error = ERR_get_error()))
1132             err("SSL: %s", ERR_error_string(error, NULL));
1133         errx("Failed to load certificate");
1134     }
1135     if (!SSL_CTX_use_PrivateKey_file(ssl_ctx_srv, "/tmp/server.key", SSL_FILETYPE_PEM)) {
1136         while ((error = ERR_get_error()))
1137             err("SSL: %s", ERR_error_string(error, NULL));
1138         errx("Failed to load private key");
1139     }
1140     return tlslistener(ssl_ctx_srv);
1141 }