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