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