4851b287787690f19d00e21072388824be2c0310
[radsecproxy.git] / radsecproxy.c
1 /*
2  * Copyright (C) 2006, 2007 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 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
10  *              rd is responsible for init and launching wr
11  * For TLS there is a server instance that launches tlsserverrd for each TLS peer
12  *          each tlsserverrd launches tlsserverwr
13  * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
14  *          for init and launching rd
15  *
16  * serverrd will receive a request, processes it and puts it in the requestq of
17  *          the appropriate clientwr
18  * clientwr monitors its requestq and sends requests
19  * clientrd looks for responses, processes them and puts them in the replyq of
20  *          the peer the request came from
21  * serverwr monitors its reply and sends replies
22  *
23  * In addition to the main thread, we have:
24  * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
25  * If TLS peers are configured, there will initially be 2 * #peers TLS threads
26  * For each TLS peer connecting to us there will be 2 more TLS threads
27  *       This is only for connected peers
28  * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
29  *          1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
30 */
31
32 #include <sys/socket.h>
33 #include <netinet/in.h>
34 #include <netdb.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <sys/time.h>
38 #include <regex.h>
39 #include <libgen.h>
40 #include <pthread.h>
41 #include <openssl/ssl.h>
42 #include <openssl/rand.h>
43 #include <openssl/err.h>
44 #include <openssl/md5.h>
45 #include <openssl/hmac.h>
46 #include "debug.h"
47 #include "radsecproxy.h"
48
49 static struct options options;
50 static struct client *clients = NULL;
51 static struct server *servers = NULL;
52 static struct realm *realms = NULL;
53 static struct tls *tls = NULL;
54
55 static int client_udp_count = 0;
56 static int client_tls_count = 0;
57 static int client_count = 0;
58 static int server_udp_count = 0;
59 static int server_tls_count = 0;
60 static int server_count = 0;
61 static int realm_count = 0;
62 static int tls_count = 0;
63
64 static struct peer *tcp_server_listen;
65 static struct peer *udp_server_listen;
66 static struct replyq udp_server_replyq;
67 static int udp_server_sock = -1;
68 static pthread_mutex_t *ssl_locks;
69 static long *ssl_lock_count;
70 extern int optind;
71 extern char *optarg;
72
73 /* callbacks for making OpenSSL thread safe */
74 unsigned long ssl_thread_id() {
75         return (unsigned long)pthread_self();
76 }
77
78 void ssl_locking_callback(int mode, int type, const char *file, int line) {
79     if (mode & CRYPTO_LOCK) {
80         pthread_mutex_lock(&ssl_locks[type]);
81         ssl_lock_count[type]++;
82     } else
83         pthread_mutex_unlock(&ssl_locks[type]);
84 }
85
86 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
87     int pwdlen = strlen(userdata);
88     if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
89         return 0;
90     memcpy(buf, userdata, pwdlen);
91     return pwdlen;
92 }
93
94 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
95   char buf[256];
96   X509 *err_cert;
97   int err, depth;
98
99   err_cert = X509_STORE_CTX_get_current_cert(ctx);
100   err = X509_STORE_CTX_get_error(ctx);
101   depth = X509_STORE_CTX_get_error_depth(ctx);
102
103   if (depth > MAX_CERT_DEPTH) {
104       ok = 0;
105       err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
106       X509_STORE_CTX_set_error(ctx, err);
107   }
108
109   if (!ok) {
110       X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
111       debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
112
113       switch (err) {
114       case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
115           X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
116           debug(DBG_WARN, "\tIssuer=%s", buf);
117           break;
118       case X509_V_ERR_CERT_NOT_YET_VALID:
119       case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
120           debug(DBG_WARN, "\tCertificate not yet valid");
121           break;
122       case X509_V_ERR_CERT_HAS_EXPIRED:
123           debug(DBG_WARN, "Certificate has expired");
124           break;
125       case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
126           debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
127           break;
128       }
129   }
130 #ifdef DEBUG  
131   printf("certificate verify returns %d\n", ok);
132 #endif  
133   return ok;
134 }
135
136 #ifdef DEBUG
137 void printauth(char *s, unsigned char *t) {
138     int i;
139     printf("%s:", s);
140     for (i = 0; i < 16; i++)
141             printf("%02x ", t[i]);
142     printf("\n");
143 }
144 #endif
145
146 int resolvepeer(struct peer *peer, int ai_flags) {
147     struct addrinfo hints, *addrinfo;
148     
149     memset(&hints, 0, sizeof(hints));
150     hints.ai_socktype = (peer->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
151     hints.ai_family = AF_UNSPEC;
152     hints.ai_flags = ai_flags;
153     if (getaddrinfo(peer->host, peer->port, &hints, &addrinfo)) {
154         debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", peer->host, peer->port);
155         return 0;
156     }
157
158     if (peer->addrinfo)
159         freeaddrinfo(peer->addrinfo);
160     peer->addrinfo = addrinfo;
161     return 1;
162 }         
163
164 int connecttoserver(struct addrinfo *addrinfo) {
165     int s;
166     struct addrinfo *res;
167
168     s = -1;
169     for (res = addrinfo; res; res = res->ai_next) {
170         s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
171         if (s < 0) {
172             debug(DBG_WARN, "connecttoserver: socket failed");
173             continue;
174         }
175         if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
176             break;
177         debug(DBG_WARN, "connecttoserver: connect failed");
178         close(s);
179         s = -1;
180     }
181     return s;
182 }         
183
184 int bindtoaddr(struct addrinfo *addrinfo) {
185     int s, on = 1;
186     struct addrinfo *res;
187     
188     for (res = addrinfo; res; res = res->ai_next) {
189         s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
190         if (s < 0) {
191             debug(DBG_WARN, "bindtoaddr: socket failed");
192             continue;
193         }
194         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
195         if (!bind(s, res->ai_addr, res->ai_addrlen))
196             return s;
197         debug(DBG_WARN, "bindtoaddr: bind failed");
198         close(s);
199     }
200     return -1;
201 }         
202
203 /* returns the client with matching address, or NULL */
204 /* if client argument is not NULL, we only check that one client */
205 struct client *find_client(char type, struct sockaddr *addr, struct client *client) {
206     struct sockaddr_in6 *sa6 = NULL;
207     struct in_addr *a4 = NULL;
208     struct client *c;
209     int i;
210     struct addrinfo *res;
211
212     if (addr->sa_family == AF_INET6) {
213         sa6 = (struct sockaddr_in6 *)addr;
214         if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
215             a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
216     } else
217         a4 = &((struct sockaddr_in *)addr)->sin_addr;
218
219     c = (client ? client : clients);
220     for (i = 0; i < client_count; i++) {
221         if (c->peer.type == type)
222             for (res = c->peer.addrinfo; res; res = res->ai_next)
223                 if ((a4 && res->ai_family == AF_INET &&
224                      !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
225                     (sa6 && res->ai_family == AF_INET6 &&
226                      !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
227                     return c;
228         if (client)
229             break;
230         c++;
231     }
232     return NULL;
233 }
234
235 /* returns the server with matching address, or NULL */
236 /* if server argument is not NULL, we only check that one server */
237 struct server *find_server(char type, struct sockaddr *addr, struct server *server) {
238     struct sockaddr_in6 *sa6 = NULL;
239     struct in_addr *a4 = NULL;
240     struct server *s;
241     int i;
242     struct addrinfo *res;
243
244     if (addr->sa_family == AF_INET6) {
245         sa6 = (struct sockaddr_in6 *)addr;
246         if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
247             a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
248     } else
249         a4 = &((struct sockaddr_in *)addr)->sin_addr;
250
251     s = (server ? server : servers);
252     for (i = 0; i < server_count; i++) {
253         if (s->peer.type == type)
254             for (res = s->peer.addrinfo; res; res = res->ai_next)
255                 if ((a4 && res->ai_family == AF_INET &&
256                      !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
257                     (sa6 && res->ai_family == AF_INET6 &&
258                      !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
259                     return s;
260         if (server)
261             break;
262         s++;
263     }
264     return NULL;
265 }
266
267 /* exactly one of client and server must be non-NULL */
268 /* if *peer == NULL we return who we received from, else require it to be from peer */
269 /* return from in sa if not NULL */
270 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
271     int cnt, len;
272     void *f;
273     unsigned char buf[65536], *rad;
274     struct sockaddr_storage from;
275     socklen_t fromlen = sizeof(from);
276
277     for (;;) {
278         cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
279         if (cnt == -1) {
280             debug(DBG_WARN, "radudpget: recv failed");
281             continue;
282         }
283         debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
284
285         if (cnt < 20) {
286             debug(DBG_WARN, "radudpget: packet too small");
287             continue;
288         }
289     
290         len = RADLEN(buf);
291         if (len < 20) {
292             debug(DBG_WARN, "radudpget: length too small");
293             continue;
294         }
295
296         if (cnt < len) {
297             debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
298             continue;
299         }
300         if (cnt > len)
301             debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
302
303         f = (client
304              ? (void *)find_client('U', (struct sockaddr *)&from, *client)
305              : (void *)find_server('U', (struct sockaddr *)&from, *server));
306         if (!f) {
307             debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer, ignoring");
308             continue;
309         }
310
311         rad = malloc(len);
312         if (rad)
313             break;
314         debug(DBG_ERR, "radudpget: malloc failed");
315     }
316     memcpy(rad, buf, len);
317     if (client)
318         *client = (struct client *)f; /* only need this if *client == NULL, but if not NULL *client == f here */
319     else
320         *server = (struct server *)f; /* only need this if *server == NULL, but if not NULL *server == f here */
321     if (sa)
322         *sa = from;
323     return rad;
324 }
325
326 int tlsverifycert(struct peer *peer) {
327     int l, loc;
328     X509 *cert;
329     X509_NAME *nm;
330     X509_NAME_ENTRY *e;
331     unsigned char *v;
332     unsigned long error;
333
334     if (SSL_get_verify_result(peer->ssl) != X509_V_OK) {
335         debug(DBG_ERR, "tlsverifycert: basic validation failed");
336         while ((error = ERR_get_error()))
337             debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
338         return 0;
339     }
340
341     cert = SSL_get_peer_certificate(peer->ssl);
342     if (!cert) {
343         debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
344         return 0;
345     }
346     nm = X509_get_subject_name(cert);
347     loc = -1;
348     for (;;) {
349         loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
350         if (loc == -1)
351             break;
352         e = X509_NAME_get_entry(nm, loc);
353         l = ASN1_STRING_to_UTF8(&v, X509_NAME_ENTRY_get_data(e));
354         if (l < 0)
355             continue;
356 #ifdef DEBUG
357         {
358             int i;
359             printf("cn: ");
360             for (i = 0; i < l; i++)
361                 printf("%c", v[i]);
362             printf("\n");
363         }
364 #endif  
365         if (l == strlen(peer->host) && !strncasecmp(peer->host, (char *)v, l)) {
366             debug(DBG_DBG, "tlsverifycert: Found cn matching host %s, All OK", peer->host);
367             return 1;
368         }
369         debug(DBG_ERR, "tlsverifycert: cn not matching host %s", peer->host);
370     }
371     X509_free(cert);
372     return 0;
373 }
374
375 void tlsconnect(struct server *server, struct timeval *when, char *text) {
376     struct timeval now;
377     time_t elapsed;
378
379     debug(DBG_DBG, "tlsconnect called from %s", text);
380     pthread_mutex_lock(&server->lock);
381     if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
382         /* already reconnected, nothing to do */
383         debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
384         pthread_mutex_unlock(&server->lock);
385         return;
386     }
387
388     debug(DBG_DBG, "tlsconnect %s", text);
389
390     for (;;) {
391         gettimeofday(&now, NULL);
392         elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
393         if (server->connectionok) {
394             server->connectionok = 0;
395             sleep(10);
396         } else if (elapsed < 5)
397             sleep(10);
398         else if (elapsed < 300) {
399             debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
400             sleep(elapsed);
401         } else if (elapsed < 100000) {
402             debug(DBG_INFO, "tlsconnect: sleeping %ds", 600);
403             sleep(600);
404         } else
405             server->lastconnecttry.tv_sec = now.tv_sec;  /* no sleep at startup */
406         debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->peer.host, server->peer.port);
407         if (server->sock >= 0)
408             close(server->sock);
409         if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0) {
410             debug(DBG_ERR, "tlsconnect: connecttoserver failed");
411             continue;
412         }
413         
414         SSL_free(server->peer.ssl);
415         server->peer.ssl = SSL_new(server->peer.ssl_ctx);
416         SSL_set_fd(server->peer.ssl, server->sock);
417         if (SSL_connect(server->peer.ssl) > 0 && tlsverifycert(&server->peer))
418             break;
419     }
420     debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->peer.host, server->peer.port);
421     gettimeofday(&server->lastconnecttry, NULL);
422     pthread_mutex_unlock(&server->lock);
423 }
424
425 unsigned char *radtlsget(SSL *ssl) {
426     int cnt, total, len;
427     unsigned char buf[4], *rad;
428
429     for (;;) {
430         for (total = 0; total < 4; total += cnt) {
431             cnt = SSL_read(ssl, buf + total, 4 - total);
432             if (cnt <= 0) {
433                 debug(DBG_ERR, "radtlsget: connection lost");
434                 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
435                     /* remote end sent close_notify, send one back */
436                     SSL_shutdown(ssl);
437                 }
438                 return NULL;
439             }
440         }
441
442         len = RADLEN(buf);
443         rad = malloc(len);
444         if (!rad) {
445             debug(DBG_ERR, "radtlsget: malloc failed");
446             continue;
447         }
448         memcpy(rad, buf, 4);
449
450         for (; total < len; total += cnt) {
451             cnt = SSL_read(ssl, rad + total, len - total);
452             if (cnt <= 0) {
453                 debug(DBG_ERR, "radtlsget: connection lost");
454                 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
455                     /* remote end sent close_notify, send one back */
456                     SSL_shutdown(ssl);
457                 }
458                 free(rad);
459                 return NULL;
460             }
461         }
462     
463         if (total >= 20)
464             break;
465         
466         free(rad);
467         debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
468     }
469     
470     debug(DBG_DBG, "radtlsget: got %d bytes", total);
471     return rad;
472 }
473
474 int clientradput(struct server *server, unsigned char *rad) {
475     int cnt;
476     size_t len;
477     unsigned long error;
478     struct timeval lastconnecttry;
479     
480     len = RADLEN(rad);
481     if (server->peer.type == 'U') {
482         if (send(server->sock, rad, len, 0) >= 0) {
483             debug(DBG_DBG, "clienradput: sent UDP of length %d to %s port %s", len, server->peer.host, server->peer.port);
484             return 1;
485         }
486         debug(DBG_WARN, "clientradput: send failed");
487         return 0;
488     }
489
490     lastconnecttry = server->lastconnecttry;
491     while ((cnt = SSL_write(server->peer.ssl, rad, len)) <= 0) {
492         while ((error = ERR_get_error()))
493             debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
494         tlsconnect(server, &lastconnecttry, "clientradput");
495         lastconnecttry = server->lastconnecttry;
496     }
497
498     server->connectionok = 1;
499     debug(DBG_DBG, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s",
500            cnt, len, server->peer.host);
501     return 1;
502 }
503
504 int radsign(unsigned char *rad, unsigned char *sec) {
505     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
506     static unsigned char first = 1;
507     static EVP_MD_CTX mdctx;
508     unsigned int md_len;
509     int result;
510     
511     pthread_mutex_lock(&lock);
512     if (first) {
513         EVP_MD_CTX_init(&mdctx);
514         first = 0;
515     }
516
517     result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
518         EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
519         EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
520         EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
521         md_len == 16);
522     pthread_mutex_unlock(&lock);
523     return result;
524 }
525
526 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
527     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
528     static unsigned char first = 1;
529     static EVP_MD_CTX mdctx;
530     unsigned char hash[EVP_MAX_MD_SIZE];
531     unsigned int len;
532     int result;
533     
534     pthread_mutex_lock(&lock);
535     if (first) {
536         EVP_MD_CTX_init(&mdctx);
537         first = 0;
538     }
539
540     len = RADLEN(rad);
541     
542     result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
543               EVP_DigestUpdate(&mdctx, rad, 4) &&
544               EVP_DigestUpdate(&mdctx, reqauth, 16) &&
545               (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
546               EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
547               EVP_DigestFinal_ex(&mdctx, hash, &len) &&
548               len == 16 &&
549               !memcmp(hash, rad + 4, 16));
550     pthread_mutex_unlock(&lock);
551     return result;
552 }
553               
554 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
555     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
556     static unsigned char first = 1;
557     static HMAC_CTX hmacctx;
558     unsigned int md_len;
559     uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
560     
561     pthread_mutex_lock(&lock);
562     if (first) {
563         HMAC_CTX_init(&hmacctx);
564         first = 0;
565     }
566
567     memcpy(auth, authattr, 16);
568     memset(authattr, 0, 16);
569     md_len = 0;
570     HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
571     HMAC_Update(&hmacctx, rad, RADLEN(rad));
572     HMAC_Final(&hmacctx, hash, &md_len);
573     memcpy(authattr, auth, 16);
574     if (md_len != 16) {
575         debug(DBG_WARN, "message auth computation failed");
576         pthread_mutex_unlock(&lock);
577         return 0;
578     }
579
580     if (memcmp(auth, hash, 16)) {
581         debug(DBG_WARN, "message authenticator, wrong value");
582         pthread_mutex_unlock(&lock);
583         return 0;
584     }   
585         
586     pthread_mutex_unlock(&lock);
587     return 1;
588 }
589
590 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
591     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
592     static unsigned char first = 1;
593     static HMAC_CTX hmacctx;
594     unsigned int md_len;
595
596     if (!authattrval)
597         return 1;
598     
599     pthread_mutex_lock(&lock);
600     if (first) {
601         HMAC_CTX_init(&hmacctx);
602         first = 0;
603     }
604
605     memset(authattrval, 0, 16);
606     md_len = 0;
607     HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
608     HMAC_Update(&hmacctx, rad, RADLEN(rad));
609     HMAC_Final(&hmacctx, authattrval, &md_len);
610     if (md_len != 16) {
611         debug(DBG_WARN, "message auth computation failed");
612         pthread_mutex_unlock(&lock);
613         return 0;
614     }
615
616     pthread_mutex_unlock(&lock);
617     return 1;
618 }
619
620 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
621     while (length > 1) {
622         if (ATTRTYPE(attrs) == type)
623             return attrs;
624         length -= ATTRLEN(attrs);
625         attrs += ATTRLEN(attrs);
626     }
627     return NULL;
628 }
629
630 void sendrq(struct server *to, struct request *rq) {
631     int i;
632     uint8_t *attr;
633
634     pthread_mutex_lock(&to->newrq_mutex);
635     /* might simplify if only try nextid, might be ok */
636     for (i = to->nextid; i < MAX_REQUESTS; i++)
637         if (!to->requests[i].buf)
638             break;
639     if (i == MAX_REQUESTS) {
640         for (i = 0; i < to->nextid; i++)
641             if (!to->requests[i].buf)
642                 break;
643         if (i == to->nextid) {
644             debug(DBG_WARN, "No room in queue, dropping request");
645             free(rq->buf);
646             pthread_mutex_unlock(&to->newrq_mutex);
647             return;
648         }
649     }
650     
651     rq->buf[1] = (char)i;
652
653     attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
654     if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->peer.secret)) {
655         free(rq->buf);
656         pthread_mutex_unlock(&to->newrq_mutex);
657         return;
658     }
659
660     debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->peer.host);
661     to->requests[i] = *rq;
662     to->nextid = i + 1;
663
664     if (!to->newrq) {
665         to->newrq = 1;
666         debug(DBG_DBG, "signalling client writer");
667         pthread_cond_signal(&to->newrq_cond);
668     }
669     pthread_mutex_unlock(&to->newrq_mutex);
670 }
671
672 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
673     struct replyq *replyq = to->replyq;
674     
675     if (!radsign(buf, (unsigned char *)to->peer.secret)) {
676         free(buf);
677         debug(DBG_WARN, "sendreply: failed to sign message");
678         return;
679     }
680         
681     pthread_mutex_lock(&replyq->count_mutex);
682     if (replyq->count == replyq->size) {
683         debug(DBG_WARN, "No room in queue, dropping request");
684         pthread_mutex_unlock(&replyq->count_mutex);
685         free(buf);
686         return;
687     }
688
689     replyq->replies[replyq->count].buf = buf;
690     if (tosa)
691         replyq->replies[replyq->count].tosa = *tosa;
692     replyq->count++;
693
694     if (replyq->count == 1) {
695         debug(DBG_DBG, "signalling server writer");
696         pthread_cond_signal(&replyq->count_cond);
697     }
698     pthread_mutex_unlock(&replyq->count_mutex);
699 }
700
701 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
702     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
703     static unsigned char first = 1;
704     static EVP_MD_CTX mdctx;
705     unsigned char hash[EVP_MAX_MD_SIZE], *input;
706     unsigned int md_len;
707     uint8_t i, offset = 0, out[128];
708     
709     pthread_mutex_lock(&lock);
710     if (first) {
711         EVP_MD_CTX_init(&mdctx);
712         first = 0;
713     }
714
715     input = auth;
716     for (;;) {
717         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
718             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
719             !EVP_DigestUpdate(&mdctx, input, 16) ||
720             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
721             md_len != 16) {
722             pthread_mutex_unlock(&lock);
723             return 0;
724         }
725         for (i = 0; i < 16; i++)
726             out[offset + i] = hash[i] ^ in[offset + i];
727         input = out + offset - 16;
728         offset += 16;
729         if (offset == len)
730             break;
731     }
732     memcpy(in, out, len);
733     pthread_mutex_unlock(&lock);
734     return 1;
735 }
736
737 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
738     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
739     static unsigned char first = 1;
740     static EVP_MD_CTX mdctx;
741     unsigned char hash[EVP_MAX_MD_SIZE], *input;
742     unsigned int md_len;
743     uint8_t i, offset = 0, out[128];
744     
745     pthread_mutex_lock(&lock);
746     if (first) {
747         EVP_MD_CTX_init(&mdctx);
748         first = 0;
749     }
750
751     input = auth;
752     for (;;) {
753         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
754             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
755             !EVP_DigestUpdate(&mdctx, input, 16) ||
756             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
757             md_len != 16) {
758             pthread_mutex_unlock(&lock);
759             return 0;
760         }
761         for (i = 0; i < 16; i++)
762             out[offset + i] = hash[i] ^ in[offset + i];
763         input = in + offset;
764         offset += 16;
765         if (offset == len)
766             break;
767     }
768     memcpy(in, out, len);
769     pthread_mutex_unlock(&lock);
770     return 1;
771 }
772
773 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
774     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
775     static unsigned char first = 1;
776     static EVP_MD_CTX mdctx;
777     unsigned char hash[EVP_MAX_MD_SIZE];
778     unsigned int md_len;
779     uint8_t i, offset;
780     
781     pthread_mutex_lock(&lock);
782     if (first) {
783         EVP_MD_CTX_init(&mdctx);
784         first = 0;
785     }
786
787 #if 0    
788     printf("msppencrypt auth in: ");
789     for (i = 0; i < 16; i++)
790         printf("%02x ", auth[i]);
791     printf("\n");
792     
793     printf("msppencrypt salt in: ");
794     for (i = 0; i < 2; i++)
795         printf("%02x ", salt[i]);
796     printf("\n");
797     
798     printf("msppencrypt in: ");
799     for (i = 0; i < len; i++)
800         printf("%02x ", text[i]);
801     printf("\n");
802 #endif
803     
804     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
805         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
806         !EVP_DigestUpdate(&mdctx, auth, 16) ||
807         !EVP_DigestUpdate(&mdctx, salt, 2) ||
808         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
809         pthread_mutex_unlock(&lock);
810         return 0;
811     }
812
813 #if 0    
814     printf("msppencrypt hash: ");
815     for (i = 0; i < 16; i++)
816         printf("%02x ", hash[i]);
817     printf("\n");
818 #endif
819     
820     for (i = 0; i < 16; i++)
821         text[i] ^= hash[i];
822     
823     for (offset = 16; offset < len; offset += 16) {
824 #if 0   
825         printf("text + offset - 16 c(%d): ", offset / 16);
826         for (i = 0; i < 16; i++)
827             printf("%02x ", (text + offset - 16)[i]);
828         printf("\n");
829 #endif
830         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
831             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
832             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
833             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
834             md_len != 16) {
835             pthread_mutex_unlock(&lock);
836             return 0;
837         }
838 #if 0   
839         printf("msppencrypt hash: ");
840         for (i = 0; i < 16; i++)
841             printf("%02x ", hash[i]);
842         printf("\n");
843 #endif    
844         
845         for (i = 0; i < 16; i++)
846             text[offset + i] ^= hash[i];
847     }
848     
849 #if 0
850     printf("msppencrypt out: ");
851     for (i = 0; i < len; i++)
852         printf("%02x ", text[i]);
853     printf("\n");
854 #endif
855
856     pthread_mutex_unlock(&lock);
857     return 1;
858 }
859
860 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
861     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
862     static unsigned char first = 1;
863     static EVP_MD_CTX mdctx;
864     unsigned char hash[EVP_MAX_MD_SIZE];
865     unsigned int md_len;
866     uint8_t i, offset;
867     char plain[255];
868     
869     pthread_mutex_lock(&lock);
870     if (first) {
871         EVP_MD_CTX_init(&mdctx);
872         first = 0;
873     }
874
875 #if 0    
876     printf("msppdecrypt auth in: ");
877     for (i = 0; i < 16; i++)
878         printf("%02x ", auth[i]);
879     printf("\n");
880     
881     printf("msppedecrypt salt in: ");
882     for (i = 0; i < 2; i++)
883         printf("%02x ", salt[i]);
884     printf("\n");
885     
886     printf("msppedecrypt in: ");
887     for (i = 0; i < len; i++)
888         printf("%02x ", text[i]);
889     printf("\n");
890 #endif
891     
892     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
893         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
894         !EVP_DigestUpdate(&mdctx, auth, 16) ||
895         !EVP_DigestUpdate(&mdctx, salt, 2) ||
896         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
897         pthread_mutex_unlock(&lock);
898         return 0;
899     }
900
901 #if 0    
902     printf("msppedecrypt hash: ");
903     for (i = 0; i < 16; i++)
904         printf("%02x ", hash[i]);
905     printf("\n");
906 #endif
907     
908     for (i = 0; i < 16; i++)
909         plain[i] = text[i] ^ hash[i];
910     
911     for (offset = 16; offset < len; offset += 16) {
912 #if 0   
913         printf("text + offset - 16 c(%d): ", offset / 16);
914         for (i = 0; i < 16; i++)
915             printf("%02x ", (text + offset - 16)[i]);
916         printf("\n");
917 #endif
918         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
919             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
920             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
921             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
922             md_len != 16) {
923             pthread_mutex_unlock(&lock);
924             return 0;
925         }
926 #if 0   
927     printf("msppedecrypt hash: ");
928     for (i = 0; i < 16; i++)
929         printf("%02x ", hash[i]);
930     printf("\n");
931 #endif    
932
933     for (i = 0; i < 16; i++)
934         plain[offset + i] = text[offset + i] ^ hash[i];
935     }
936
937     memcpy(text, plain, len);
938 #if 0
939     printf("msppedecrypt out: ");
940     for (i = 0; i < len; i++)
941         printf("%02x ", text[i]);
942     printf("\n");
943 #endif
944
945     pthread_mutex_unlock(&lock);
946     return 1;
947 }
948
949 struct realm *id2realm(char *id, uint8_t len) {
950     int i;
951     for (i = 0; i < realm_count; i++)
952         if (!regexec(&realms[i].regex, id, 0, NULL, 0)) {
953             debug(DBG_DBG, "found matching realm: %s", realms[i].name);
954             return realms + i;
955         }
956     return NULL;
957 }
958
959 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
960     int i;
961     
962     pthread_mutex_lock(&to->newrq_mutex);
963     for (i = 0; i < MAX_REQUESTS; i++)
964         if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
965             break;
966     pthread_mutex_unlock(&to->newrq_mutex);
967     
968     return i < MAX_REQUESTS;
969 }
970
971 int attrvalidate(unsigned char *attrs, int length) {
972     while (length > 1) {
973         if (ATTRLEN(attrs) < 2) {
974             debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
975             return 0;
976         }
977         length -= ATTRLEN(attrs);
978         if (length < 0) {
979             debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
980             return 0;
981         }
982         attrs += ATTRLEN(attrs);
983     }
984     if (length)
985         debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
986     return 1;
987 }
988
989 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
990 #ifdef DEBUG    
991     int i;
992 #endif    
993     if (len < 16 || len > 128 || len % 16) {
994         debug(DBG_WARN, "pwdrecrypt: invalid password length");
995         return 0;
996     }
997         
998     if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
999         debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1000         return 0;
1001     }
1002 #ifdef DEBUG
1003     printf("pwdrecrypt: password: ");
1004     for (i = 0; i < len; i++)
1005         printf("%02x ", pwd[i]);
1006     printf("\n");
1007 #endif  
1008     if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1009         debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1010         return 0;
1011     }
1012     return 1;
1013 }
1014
1015 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1016     if (len < 18)
1017         return 0;
1018     if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1019         debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1020         return 0;
1021     }
1022     if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1023         debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1024         return 0;
1025     }
1026     return 1;
1027 }
1028
1029 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1030            char *oldsecret, char *newsecret) {
1031     unsigned char *attr;
1032     
1033     for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1034         debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1035         if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1036             return 0;
1037     }
1038     return 1;
1039 }
1040
1041 void respondstatusserver(struct request *rq) {
1042     unsigned char *resp;
1043
1044     resp = malloc(20);
1045     if (!resp) {
1046         debug(DBG_ERR, "respondstatusserver: malloc failed");
1047         return;
1048     }
1049     memcpy(resp, rq->buf, 20);
1050     resp[0] = RAD_Access_Accept;
1051     resp[2] = 0;
1052     resp[3] = 20;
1053     debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->peer.host);
1054     sendreply(rq->from, resp, rq->from->peer.type == 'U' ? &rq->fromsa : NULL);
1055 }
1056
1057 void respondreject(struct request *rq, char *message) {
1058     unsigned char *resp;
1059     int len = 20;
1060
1061     if (message)
1062         len += 2 + strlen(message);
1063     
1064     resp = malloc(len);
1065     if (!resp) {
1066         debug(DBG_ERR, "respondreject: malloc failed");
1067         return;
1068     }
1069     memcpy(resp, rq->buf, 20);
1070     resp[0] = RAD_Access_Reject;
1071     *(uint16_t *)(resp + 2) = htons(len);
1072     if (message) {
1073         resp[20] = RAD_Attr_Reply_Message;
1074         resp[21] = len - 20;
1075         memcpy(resp + 22, message, len - 22);
1076     }
1077     sendreply(rq->from, resp, rq->from->peer.type == 'U' ? &rq->fromsa : NULL);
1078 }
1079
1080 void radsrv(struct request *rq) {
1081     uint8_t code, id, *auth, *attrs, *attr;
1082     uint16_t len;
1083     struct server *to = NULL;
1084     char username[256];
1085     unsigned char *buf, newauth[16];
1086     struct realm *realm = NULL;
1087     
1088     buf = rq->buf;
1089     code = *(uint8_t *)buf;
1090     id = *(uint8_t *)(buf + 1);
1091     len = RADLEN(buf);
1092     auth = (uint8_t *)(buf + 4);
1093
1094     debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1095     
1096     if (code != RAD_Access_Request && code != RAD_Status_Server) {
1097         debug(DBG_INFO, "radsrv: server currently accepts only access-requests and status-server, ignoring");
1098         free(buf);
1099         return;
1100     }
1101
1102     len -= 20;
1103     attrs = buf + 20;
1104
1105     if (!attrvalidate(attrs, len)) {
1106         debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1107         free(buf);
1108         return;
1109     }
1110
1111     if (code == RAD_Access_Request) {
1112         attr = attrget(attrs, len, RAD_Attr_User_Name);
1113         if (!attr) {
1114             debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1115             free(buf);
1116             return;
1117         }
1118         memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1119         username[ATTRVALLEN(attr)] = '\0';
1120         debug(DBG_DBG, "Access Request with username: %s", username);
1121
1122         realm = id2realm(username, strlen(username));
1123         if (!realm) {
1124             debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1125             free(buf);
1126             return;
1127         }
1128         to = realm->server;
1129
1130         if (to && rqinqueue(to, rq->from, id)) {
1131             debug(DBG_INFO, "radsrv: already got request from host %s with id %d, ignoring", rq->from->peer.host, id);
1132             free(buf);
1133             return;
1134         }
1135     }
1136     
1137     attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1138     if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(buf, ATTRVAL(attr), rq->from->peer.secret))) {
1139         debug(DBG_WARN, "radsrv: message authentication failed");
1140         free(buf);
1141         return;
1142     }
1143     
1144     if (code == RAD_Status_Server) {
1145         respondstatusserver(rq);
1146         return;
1147     }
1148
1149     if (!to) {
1150         debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->peer.host, username);
1151         respondreject(rq, realm->message);
1152         return;
1153     }
1154     
1155     if (!RAND_bytes(newauth, 16)) {
1156         debug(DBG_WARN, "radsrv: failed to generate random auth");
1157         free(buf);
1158         return;
1159     }
1160
1161 #ifdef DEBUG    
1162     printauth("auth", auth);
1163 #endif
1164
1165     attr = attrget(attrs, len, RAD_Attr_User_Password);
1166     if (attr) {
1167         debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1168         if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->peer.secret, to->peer.secret, auth, newauth)) {
1169             free(buf);
1170             return;
1171         }
1172     }
1173     
1174     attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1175     if (attr) {
1176         debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1177         if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->peer.secret, to->peer.secret, auth, newauth)) {
1178             free(buf);
1179             return;
1180         }
1181     }
1182
1183     rq->origid = id;
1184     memcpy(rq->origauth, auth, 16);
1185     memcpy(auth, newauth, 16);
1186     sendrq(to, rq);
1187 }
1188
1189 void *clientrd(void *arg) {
1190     struct server *server = (struct server *)arg;
1191     struct client *from;
1192     int i, len, sublen;
1193     unsigned char *buf, *messageauth, *subattrs, *attrs, *attr;
1194     struct sockaddr_storage fromsa;
1195     struct timeval lastconnecttry;
1196     char tmp[256];
1197     
1198     for (;;) {
1199         lastconnecttry = server->lastconnecttry;
1200         buf = (server->peer.type == 'U' ? radudpget(server->sock, NULL, &server, NULL) : radtlsget(server->peer.ssl));
1201         if (!buf && server->peer.type == 'T') {
1202             tlsconnect(server, &lastconnecttry, "clientrd");
1203             continue;
1204         }
1205     
1206         server->connectionok = 1;
1207
1208         i = buf[1]; /* i is the id */
1209
1210         switch (*buf) {
1211         case RAD_Access_Accept:
1212             debug(DBG_DBG, "got Access Accept with id %d", i);
1213             break;
1214         case RAD_Access_Reject:
1215             debug(DBG_DBG, "got Access Reject with id %d", i);
1216             break;
1217         case RAD_Access_Challenge:
1218             debug(DBG_DBG, "got Access Challenge with id %d", i);
1219             break;
1220         default:
1221             free(buf);
1222             debug(DBG_INFO, "clientrd: discarding, only accept access accept, access reject and access challenge messages");
1223             continue;
1224         }
1225         
1226         pthread_mutex_lock(&server->newrq_mutex);
1227         if (!server->requests[i].buf || !server->requests[i].tries) {
1228             pthread_mutex_unlock(&server->newrq_mutex);
1229             free(buf);
1230             debug(DBG_INFO, "clientrd: no matching request sent with this id, ignoring");
1231             continue;
1232         }
1233
1234         if (server->requests[i].received) {
1235             pthread_mutex_unlock(&server->newrq_mutex);
1236             free(buf);
1237             debug(DBG_INFO, "clientrd: already received, ignoring");
1238             continue;
1239         }
1240         
1241         if (!validauth(buf, server->requests[i].buf + 4, (unsigned char *)server->peer.secret)) {
1242             pthread_mutex_unlock(&server->newrq_mutex);
1243             free(buf);
1244             debug(DBG_WARN, "clientrd: invalid auth, ignoring");
1245             continue;
1246         }
1247         
1248         from = server->requests[i].from;
1249         len = RADLEN(buf) - 20;
1250         attrs = buf + 20;
1251
1252         if (!attrvalidate(attrs, len)) {
1253             pthread_mutex_unlock(&server->newrq_mutex);
1254             free(buf);
1255             debug(DBG_WARN, "clientrd: attribute validation failed, ignoring packet");
1256             continue;
1257         }
1258         
1259         /* Message Authenticator */
1260         messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1261         if (messageauth) {
1262             if (ATTRVALLEN(messageauth) != 16) {
1263                 pthread_mutex_unlock(&server->newrq_mutex);
1264                 free(buf);
1265                 debug(DBG_WARN, "clientrd: illegal message auth attribute length, ignoring packet");
1266                 continue;
1267             }
1268             memcpy(tmp, buf + 4, 16);
1269             memcpy(buf + 4, server->requests[i].buf + 4, 16);
1270             if (!checkmessageauth(buf, ATTRVAL(messageauth), server->peer.secret)) {
1271                 pthread_mutex_unlock(&server->newrq_mutex);
1272                 free(buf);
1273                 debug(DBG_WARN, "clientrd: message authentication failed");
1274                 continue;
1275             }
1276             memcpy(buf + 4, tmp, 16);
1277             debug(DBG_DBG, "clientrd: message auth ok");
1278         }
1279         
1280         if (*server->requests[i].buf == RAD_Status_Server) {
1281             server->requests[i].received = 1;
1282             pthread_mutex_unlock(&server->newrq_mutex);
1283             free(buf);
1284             debug(DBG_INFO, "clientrd: got status server response from %s", server->peer.host);
1285             continue;
1286         }
1287
1288         /* MS MPPE */
1289         for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1290             if (ATTRVALLEN(attr) <= 4)
1291                 break;
1292             
1293             if (((uint16_t *)attr)[1] != 0 || ntohs(((uint16_t *)attr)[2]) != 311) /* 311 == MS */
1294                 continue;
1295             
1296             sublen = ATTRVALLEN(attr) - 4;
1297             subattrs = ATTRVAL(attr) + 4;  
1298             if (!attrvalidate(subattrs, sublen) ||
1299                 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1300                         server->requests + i, server->peer.secret, from->peer.secret) ||
1301                 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1302                         server->requests + i, server->peer.secret, from->peer.secret))
1303                 break;
1304         }
1305         if (attr) {
1306             pthread_mutex_unlock(&server->newrq_mutex);
1307             free(buf);
1308             debug(DBG_WARN, "clientrd: MS attribute handling failed, ignoring packet");
1309             continue;
1310         }
1311         
1312         if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject) {
1313             attr = attrget(server->requests[i].buf + 20, RADLEN(server->requests[i].buf) - 20, RAD_Attr_User_Name);
1314             /* we know the attribute exists */
1315             memcpy(tmp, ATTRVAL(attr), ATTRVALLEN(attr));
1316             tmp[ATTRVALLEN(attr)] = '\0';
1317             switch (*buf) {
1318             case RAD_Access_Accept:
1319                 debug(DBG_INFO, "Access Accept for %s from %s", tmp, server->peer.host);
1320                 break;
1321             case RAD_Access_Reject:
1322                 debug(DBG_INFO, "Access Reject for %s from %s", tmp, server->peer.host);
1323                 break;
1324             }
1325         }
1326         
1327         /* once we set received = 1, requests[i] may be reused */
1328         buf[1] = (char)server->requests[i].origid;
1329         memcpy(buf + 4, server->requests[i].origauth, 16);
1330 #ifdef DEBUG    
1331         printauth("origauth/buf+4", buf + 4);
1332 #endif
1333         
1334         if (messageauth) {
1335             if (!createmessageauth(buf, ATTRVAL(messageauth), from->peer.secret)) {
1336                 pthread_mutex_unlock(&server->newrq_mutex);
1337                 free(buf);
1338                 continue;
1339             }
1340             debug(DBG_DBG, "clientrd: computed messageauthattr");
1341         }
1342
1343         if (from->peer.type == 'U')
1344             fromsa = server->requests[i].fromsa;
1345         server->requests[i].received = 1;
1346         pthread_mutex_unlock(&server->newrq_mutex);
1347
1348         debug(DBG_DBG, "clientrd: giving packet back to where it came from");
1349         sendreply(from, buf, from->peer.type == 'U' ? &fromsa : NULL);
1350     }
1351 }
1352
1353 void *clientwr(void *arg) {
1354     struct server *server = (struct server *)arg;
1355     struct request *rq;
1356     pthread_t clientrdth;
1357     int i;
1358     uint8_t rnd;
1359     struct timeval now, lastsend;
1360     struct timespec timeout;
1361     struct request statsrvrq;
1362     unsigned char statsrvbuf[38];
1363
1364     memset(&timeout, 0, sizeof(struct timespec));
1365     
1366     if (server->statusserver) {
1367         memset(&statsrvrq, 0, sizeof(struct request));
1368         memset(statsrvbuf, 0, sizeof(statsrvbuf));
1369         statsrvbuf[0] = RAD_Status_Server;
1370         statsrvbuf[3] = 38;
1371         statsrvbuf[20] = RAD_Attr_Message_Authenticator;
1372         statsrvbuf[21] = 18;
1373         gettimeofday(&lastsend, NULL);
1374     }
1375     
1376     if (server->peer.type == 'U') {
1377         if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0)
1378             debugx(1, DBG_ERR, "clientwr: connecttoserver failed");
1379     } else
1380         tlsconnect(server, NULL, "new client");
1381     
1382     if (pthread_create(&clientrdth, NULL, clientrd, (void *)server))
1383         debugx(1, DBG_ERR, "clientwr: pthread_create failed");
1384
1385     for (;;) {
1386         pthread_mutex_lock(&server->newrq_mutex);
1387         if (!server->newrq) {
1388             gettimeofday(&now, NULL);
1389             if (server->statusserver) {
1390                 /* random 0-7 seconds */
1391                 RAND_bytes(&rnd, 1);
1392                 rnd /= 32;
1393                 if (!timeout.tv_sec || timeout.tv_sec - now.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
1394                     timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
1395             }   
1396             if (timeout.tv_sec) {
1397                 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1398                 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1399                 timeout.tv_sec = 0;
1400             } else {
1401                 debug(DBG_DBG, "clientwr: waiting for new request");
1402                 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1403             }
1404         }
1405         if (server->newrq) {
1406             debug(DBG_DBG, "clientwr: got new request");
1407             server->newrq = 0;
1408         } else
1409             debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1410         pthread_mutex_unlock(&server->newrq_mutex);
1411
1412         for (i = 0; i < MAX_REQUESTS; i++) {
1413             pthread_mutex_lock(&server->newrq_mutex);
1414             while (!server->requests[i].buf && i < MAX_REQUESTS)
1415                 i++;
1416             if (i == MAX_REQUESTS) {
1417                 pthread_mutex_unlock(&server->newrq_mutex);
1418                 break;
1419             }
1420             rq = server->requests + i;
1421
1422             if (rq->received) {
1423                 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
1424                 if (rq->buf) {
1425                     debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
1426                     free(rq->buf);
1427                     /* setting this to NULL means that it can be reused */
1428                     rq->buf = NULL;
1429                 }
1430                 pthread_mutex_unlock(&server->newrq_mutex);
1431                 continue;
1432             }
1433             
1434             gettimeofday(&now, NULL);
1435             if (now.tv_sec < rq->expiry.tv_sec) {
1436                 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1437                     timeout.tv_sec = rq->expiry.tv_sec;
1438                 pthread_mutex_unlock(&server->newrq_mutex);
1439                 continue;
1440             }
1441
1442             if (rq->tries == (*rq->buf == RAD_Status_Server || server->peer.type == 'T'
1443                               ? 1 : REQUEST_RETRIES)) {
1444                 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1445                 if (*rq->buf == RAD_Status_Server)
1446                     debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->peer.host);
1447                 free(rq->buf);
1448                 /* setting this to NULL means that it can be reused */
1449                 rq->buf = NULL;
1450                 pthread_mutex_unlock(&server->newrq_mutex);
1451                 continue;
1452             }
1453             pthread_mutex_unlock(&server->newrq_mutex);
1454
1455             rq->expiry.tv_sec = now.tv_sec +
1456                 (*rq->buf == RAD_Status_Server || server->peer.type == 'T'
1457                  ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
1458             if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1459                 timeout.tv_sec = rq->expiry.tv_sec;
1460             rq->tries++;
1461             clientradput(server, server->requests[i].buf);
1462             gettimeofday(&lastsend, NULL);
1463         }
1464         if (server->statusserver) {
1465             gettimeofday(&now, NULL);
1466             if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
1467                 if (!RAND_bytes(statsrvbuf + 4, 16)) {
1468                     debug(DBG_WARN, "clientwr: failed to generate random auth");
1469                     continue;
1470                 }
1471                 statsrvrq.buf = malloc(sizeof(statsrvbuf));
1472                 if (!statsrvrq.buf) {
1473                     debug(DBG_ERR, "clientwr: malloc failed");
1474                     continue;
1475                 }
1476                 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
1477                 debug(DBG_DBG, "clientwr: sending status server to %s", server->peer.host);
1478                 lastsend.tv_sec = now.tv_sec;
1479                 sendrq(server, &statsrvrq);
1480             }
1481         }
1482     }
1483 }
1484
1485 void *udpserverwr(void *arg) {
1486     struct replyq *replyq = &udp_server_replyq;
1487     struct reply *reply = replyq->replies;
1488     
1489     pthread_mutex_lock(&replyq->count_mutex);
1490     for (;;) {
1491         while (!replyq->count) {
1492             debug(DBG_DBG, "udp server writer, waiting for signal");
1493             pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1494             debug(DBG_DBG, "udp server writer, got signal");
1495         }
1496         pthread_mutex_unlock(&replyq->count_mutex);
1497         
1498         if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
1499                    (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
1500             debug(DBG_WARN, "sendudp: send failed");
1501         free(reply->buf);
1502         
1503         pthread_mutex_lock(&replyq->count_mutex);
1504         replyq->count--;
1505         memmove(replyq->replies, replyq->replies + 1,
1506                 replyq->count * sizeof(struct reply));
1507     }
1508 }
1509
1510 void *udpserverrd(void *arg) {
1511     struct request rq;
1512     pthread_t udpserverwrth;
1513
1514     if ((udp_server_sock = bindtoaddr(udp_server_listen->addrinfo)) < 0)
1515         debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
1516
1517     debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
1518           udp_server_listen->host ? udp_server_listen->host : "*", udp_server_listen->port);
1519
1520     if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
1521         debugx(1, DBG_ERR, "pthread_create failed");
1522     
1523     for (;;) {
1524         memset(&rq, 0, sizeof(struct request));
1525         rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
1526         radsrv(&rq);
1527     }
1528 }
1529
1530 void *tlsserverwr(void *arg) {
1531     int cnt;
1532     unsigned long error;
1533     struct client *client = (struct client *)arg;
1534     struct replyq *replyq;
1535     
1536     debug(DBG_DBG, "tlsserverwr starting for %s", client->peer.host);
1537     replyq = client->replyq;
1538     pthread_mutex_lock(&replyq->count_mutex);
1539     for (;;) {
1540         while (!replyq->count) {
1541             if (client->peer.ssl) {         
1542                 debug(DBG_DBG, "tls server writer, waiting for signal");
1543                 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1544                 debug(DBG_DBG, "tls server writer, got signal");
1545             }
1546             if (!client->peer.ssl) {
1547                 /* ssl might have changed while waiting */
1548                 pthread_mutex_unlock(&replyq->count_mutex);
1549                 debug(DBG_DBG, "tlsserverwr: exiting as requested");
1550                 pthread_exit(NULL);
1551             }
1552         }
1553         pthread_mutex_unlock(&replyq->count_mutex);
1554         cnt = SSL_write(client->peer.ssl, replyq->replies->buf, RADLEN(replyq->replies->buf));
1555         if (cnt > 0)
1556             debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
1557                   cnt, RADLEN(replyq->replies->buf));
1558         else
1559             while ((error = ERR_get_error()))
1560                 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
1561         free(replyq->replies->buf);
1562
1563         pthread_mutex_lock(&replyq->count_mutex);
1564         replyq->count--;
1565         memmove(replyq->replies, replyq->replies + 1, replyq->count * sizeof(struct reply));
1566     }
1567 }
1568
1569 void *tlsserverrd(void *arg) {
1570     struct request rq;
1571     unsigned long error;
1572     int s;
1573     struct client *client = (struct client *)arg;
1574     pthread_t tlsserverwrth;
1575     SSL *ssl;
1576     
1577     debug(DBG_DBG, "tlsserverrd starting for %s", client->peer.host);
1578     ssl = client->peer.ssl;
1579
1580     if (SSL_accept(ssl) <= 0) {
1581         while ((error = ERR_get_error()))
1582             debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
1583         debug(DBG_ERR, "SSL_accept failed");
1584         goto errexit;
1585     }
1586     if (tlsverifycert(&client->peer)) {
1587         if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
1588             debug(DBG_ERR, "tlsserverrd: pthread_create failed");
1589             goto errexit;
1590         }
1591         for (;;) {
1592             memset(&rq, 0, sizeof(struct request));
1593             rq.buf = radtlsget(client->peer.ssl);
1594             if (!rq.buf)
1595                 break;
1596             debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->peer.host);
1597             rq.from = client;
1598             radsrv(&rq);
1599         }
1600         debug(DBG_ERR, "tlsserverrd: connection lost");
1601         /* stop writer by setting peer.ssl to NULL and give signal in case waiting for data */
1602         client->peer.ssl = NULL;
1603         pthread_mutex_lock(&client->replyq->count_mutex);
1604         pthread_cond_signal(&client->replyq->count_cond);
1605         pthread_mutex_unlock(&client->replyq->count_mutex);
1606         debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
1607         pthread_join(tlsserverwrth, NULL);
1608     }
1609     
1610  errexit:
1611     s = SSL_get_fd(ssl);
1612     SSL_free(ssl);
1613     shutdown(s, SHUT_RDWR);
1614     close(s);
1615     debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->peer.host);
1616     client->peer.ssl = NULL;
1617     pthread_exit(NULL);
1618 }
1619
1620 int tlslistener() {
1621     pthread_t tlsserverth;
1622     int s, snew;
1623     struct sockaddr_storage from;
1624     size_t fromlen = sizeof(from);
1625     struct client *client;
1626
1627     if ((s = bindtoaddr(tcp_server_listen->addrinfo)) < 0)
1628         debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
1629     
1630     listen(s, 0);
1631     debug(DBG_WARN, "listening for incoming TCP on %s:%s",
1632           tcp_server_listen->host ? tcp_server_listen->host : "*", tcp_server_listen->port);
1633
1634     for (;;) {
1635         snew = accept(s, (struct sockaddr *)&from, &fromlen);
1636         if (snew < 0) {
1637             debug(DBG_WARN, "accept failed");
1638             continue;
1639         }
1640         debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
1641
1642         client = find_client('T', (struct sockaddr *)&from, NULL);
1643         if (!client) {
1644             debug(DBG_WARN, "ignoring request, not a known TLS client");
1645             shutdown(snew, SHUT_RDWR);
1646             close(snew);
1647             continue;
1648         }
1649
1650         if (client->peer.ssl) {
1651             debug(DBG_WARN, "Ignoring incoming TLS connection, already have one from this client");
1652             shutdown(snew, SHUT_RDWR);
1653             close(snew);
1654             continue;
1655         }
1656         client->peer.ssl = SSL_new(client->peer.ssl_ctx);
1657         SSL_set_fd(client->peer.ssl, snew);
1658         if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
1659             debug(DBG_ERR, "tlslistener: pthread_create failed");
1660             SSL_free(client->peer.ssl);
1661             shutdown(snew, SHUT_RDWR);
1662             close(snew);
1663             client->peer.ssl = NULL;
1664             continue;
1665         }
1666         pthread_detach(tlsserverth);
1667     }
1668     return 0;
1669 }
1670
1671 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
1672     struct tls *new;
1673     SSL_CTX *ctx;
1674     int i;
1675     unsigned long error;
1676     
1677     if (!certfile || !certkeyfile)
1678         debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
1679
1680     if (!cacertfile && !cacertpath)
1681         debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
1682
1683     if (!ssl_locks) {
1684         ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
1685         ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
1686         for (i = 0; i < CRYPTO_num_locks(); i++) {
1687             ssl_lock_count[i] = 0;
1688             pthread_mutex_init(&ssl_locks[i], NULL);
1689         }
1690         CRYPTO_set_id_callback(ssl_thread_id);
1691         CRYPTO_set_locking_callback(ssl_locking_callback);
1692
1693         SSL_load_error_strings();
1694         SSL_library_init();
1695
1696         while (!RAND_status()) {
1697             time_t t = time(NULL);
1698             pid_t pid = getpid();
1699             RAND_seed((unsigned char *)&t, sizeof(time_t));
1700             RAND_seed((unsigned char *)&pid, sizeof(pid));
1701         }
1702     }
1703     ctx = SSL_CTX_new(TLSv1_method());
1704     if (certkeypwd) {
1705         SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
1706         SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
1707     }
1708     if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
1709         !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
1710         !SSL_CTX_check_private_key(ctx) ||
1711         !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
1712         while ((error = ERR_get_error()))
1713             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
1714         debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
1715     }
1716     
1717     SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
1718     SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
1719     
1720     tls_count++;
1721     tls = realloc(tls, tls_count * sizeof(struct tls));
1722     if (!tls)
1723         debugx(1, DBG_ERR, "malloc failed");
1724     new = tls + tls_count - 1;
1725     memset(new, 0, sizeof(struct tls));
1726     new->name = stringcopy(value, 0);
1727     if (!new->name)
1728         debugx(1, DBG_ERR, "malloc failed");
1729     new->ctx = ctx;
1730     new->count = 0;
1731     debug(DBG_DBG, "tlsadd: added TLS context %s", value);
1732 }
1733
1734 void tlsfree() {
1735     int i;
1736     for (i = 0; i < tls_count; i++)
1737         if (!tls[i].count)
1738             SSL_CTX_free(tls[i].ctx);
1739     tls_count = 0;
1740     free(tls);
1741     tls = NULL;
1742 }
1743
1744 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
1745     int i, c1 = -1, c2 = -1;
1746     for (i = 0; i < tls_count; i++) {
1747         if (!strcasecmp(tls[i].name, alt1)) {
1748             c1 = i;
1749             break;
1750         }
1751         if (c2 == -1 && alt2 && !strcasecmp(tls[i].name, alt2))
1752             c2 = i;
1753     }
1754
1755     i = (c1 == -1 ? c2 : c1);
1756     if (i == -1)
1757         return NULL;
1758     tls[i].count++;
1759     return tls[i].ctx;
1760 }
1761
1762 void addrealm(char *value, char *server, char *message) {
1763     int i, n;
1764     struct realm *realm;
1765     char *s, *regex = NULL;
1766
1767     if (server) {
1768         for (i = 0; i < server_count; i++)
1769             if (!strcasecmp(server, servers[i].peer.host))
1770                 break;
1771         if (i == server_count)
1772             debugx(1, DBG_ERR, "addrealm failed, no server %s", server);
1773     }
1774     
1775     if (*value == '/') {
1776         /* regexp, remove optional trailing / if present */
1777         if (value[strlen(value) - 1] == '/')
1778             value[strlen(value) - 1] = '\0';
1779     } else {
1780         /* not a regexp, let us make it one */
1781         if (*value == '*' && !value[1])
1782             regex = stringcopy(".*", 0);
1783         else {
1784             for (n = 0, s = value; *s;)
1785                 if (*s++ == '.')
1786                     n++;
1787             regex = malloc(strlen(value) + n + 3);
1788             if (regex) {
1789                 regex[0] = '@';
1790                 for (n = 1, s = value; *s; s++) {
1791                     if (*s == '.')
1792                         regex[n++] = '\\';
1793                     regex[n++] = *s;
1794                 }
1795                 regex[n++] = '$';
1796                 regex[n] = '\0';
1797             }
1798         }
1799         if (!regex)
1800             debugx(1, DBG_ERR, "malloc failed");
1801         debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
1802     }
1803
1804     realm_count++;
1805     realms = realloc(realms, realm_count * sizeof(struct realm));
1806     if (!realms)
1807         debugx(1, DBG_ERR, "malloc failed");
1808     realm = realms + realm_count - 1;
1809     memset(realm, 0, sizeof(struct realm));
1810     realm->name = stringcopy(value, 0);
1811     if (!realm->name)
1812         debugx(1, DBG_ERR, "malloc failed");
1813     if (message && strlen(message) > 253)
1814         debugx(1, DBG_ERR, "ReplyMessage can be at most 253 bytes");
1815     realm->message = message;
1816     if (server)
1817         realm->server = servers + i;
1818     if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB))
1819         debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
1820     if (regex)
1821         free(regex);
1822     debug(DBG_DBG, "addrealm: added realm %s for server %s", value, server);
1823 }
1824
1825 char *parsehostport(char *s, struct peer *peer) {
1826     char *p, *field;
1827     int ipv6 = 0;
1828
1829     p = s;
1830     /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
1831     if (*p == '[') {
1832         p++;
1833         field = p;
1834         for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1835         if (*p != ']')
1836             debugx(1, DBG_ERR, "no ] matching initial [");
1837         ipv6 = 1;
1838     } else {
1839         field = p;
1840         for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1841     }
1842     if (field == p)
1843         debugx(1, DBG_ERR, "missing host/address");
1844
1845     peer->host = stringcopy(field, p - field);
1846     if (ipv6) {
1847         p++;
1848         if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
1849             debugx(1, DBG_ERR, "unexpected character after ]");
1850     }
1851     if (*p == ':') {
1852             /* port number or service name is specified */;
1853             field = ++p;
1854             for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1855             if (field == p)
1856                 debugx(1, DBG_ERR, "syntax error, : but no following port");
1857             peer->port = stringcopy(field, p - field);
1858     } else
1859         peer->port = stringcopy(peer->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT, 0);
1860     return p;
1861 }
1862
1863 FILE *openconfigfile(const char *filename) {
1864     FILE *f;
1865     char pathname[100], *base = NULL;
1866     
1867     f = fopen(filename, "r");
1868     if (f) {
1869         debug(DBG_DBG, "reading config file %s", filename);
1870         return f;
1871     }
1872
1873     if (strlen(filename) + 1 <= sizeof(pathname)) {
1874         /* basename() might modify the string */
1875         strcpy(pathname, filename);
1876         base = basename(pathname);
1877         f = fopen(base, "r");
1878     }
1879
1880     if (!f)
1881         debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
1882     
1883     debug(DBG_DBG, "reading config file %s", base);
1884     return f;
1885 }
1886
1887 struct peer *server_create(char type) {
1888     struct peer *server;
1889     char *conf;
1890
1891     server = malloc(sizeof(struct peer));
1892     if (!server)
1893         debugx(1, DBG_ERR, "malloc failed");
1894     memset(server, 0, sizeof(struct peer));
1895     server->type = type;
1896     conf = (type == 'T' ? options.listentcp : options.listenudp);
1897     if (conf) {
1898         parsehostport(conf, server);
1899         if (!strcmp(server->host, "*")) {
1900             free(server->host);
1901             server->host = NULL;
1902         }
1903     } else
1904         server->port = stringcopy(type == 'T' ? DEFAULT_TLS_PORT : DEFAULT_UDP_PORT, 0);
1905     if (!resolvepeer(server, AI_PASSIVE))
1906         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", server->host, server->port);
1907     return server;
1908 }
1909
1910 /* returns NULL on error, where to continue parsing if token and ok. E.g. "" will return token with empty string */
1911 char *strtokenquote(char *s, char **token, char *del, char *quote, char *comment) {
1912     char *t = s, *q, *r;
1913
1914     if (!t || !token || !del)
1915         return NULL;
1916     while (*t && strchr(del, *t))
1917         t++;
1918     if (!*t || (comment && strchr(comment, *t))) {
1919         *token = NULL;
1920         return t + 1; /* needs to be non-NULL, but value doesn't matter */
1921     }
1922     if (quote && (q = strchr(quote, *t))) {
1923         t++;
1924         r = t;
1925         while (*t && *t != *q)
1926             t++;
1927         if (!*t || (t[1] && !strchr(del, t[1])))
1928             return NULL;
1929         *t = '\0';
1930         *token = r;
1931         return t + 1;
1932     }
1933     *token = t;
1934     t++;
1935     while (*t && !strchr(del, *t))
1936         t++;
1937     *t = '\0';
1938     return t + 1;
1939 }
1940
1941 /* Parses config with following syntax:
1942  * One of these:
1943  * option-name value
1944  * option-name = value
1945  * Or:
1946  * option-name value {
1947  *     option-name [=] value
1948  *     ...
1949  * }
1950  */
1951 void getgeneralconfig(FILE *f, char *block, ...) {
1952     va_list ap;
1953     char line[1024];
1954     /* initialise lots of stuff to avoid stupid compiler warnings */
1955     char *tokens[3], *s, *opt = NULL, *val = NULL, *word, *optval, **str = NULL;
1956     int type = 0, tcount, conftype = 0;
1957     void (*cbk)(FILE *, char *, char *, char *) = NULL;
1958         
1959     while (fgets(line, 1024, f)) {
1960         s = line;
1961         for (tcount = 0; tcount < 3; tcount++) {
1962             s = strtokenquote(s, &tokens[tcount], " \t\n", "\"'", tcount ? NULL : "#");
1963             if (!s)
1964                 debugx(1, DBG_ERR, "Syntax error in line starting with: %s", line);
1965             if (!tokens[tcount])
1966                 break;
1967         }
1968         if (!tcount || **tokens == '#')
1969             continue;
1970
1971         if (**tokens == '}') {
1972             if (block)
1973                 return;
1974             debugx(1, DBG_ERR, "configuration error, found } with no matching {");
1975         }
1976             
1977         switch (tcount) {
1978         case 2:
1979             opt = tokens[0];
1980             val = tokens[1];
1981             conftype = CONF_STR;
1982             break;
1983         case 3:
1984             if (tokens[1][0] == '=' && tokens[1][1] == '\0') {
1985                 opt = tokens[0];
1986                 val = tokens[2];
1987                 conftype = CONF_STR;
1988                 break;
1989             }
1990             if (tokens[2][0] == '{' && tokens[2][1] == '\0') {
1991                 opt = tokens[0];
1992                 val = tokens[1];
1993                 conftype = CONF_CBK;
1994                 break;
1995             }
1996             /* fall through */
1997         default:
1998             if (block)
1999                 debugx(1, DBG_ERR, "configuration error in block %s, line starting with %s", block, tokens[0]);
2000             debugx(1, DBG_ERR, "configuration error, syntax error in line starting with %s", tokens[0]);
2001         }
2002
2003         if (!*val)
2004             debugx(1, DBG_ERR, "configuration error, option %s needs a non-empty value", opt);
2005         
2006         va_start(ap, block);
2007         while ((word = va_arg(ap, char *))) {
2008             type = va_arg(ap, int);
2009             switch (type) {
2010             case CONF_STR:
2011                 str = va_arg(ap, char **);
2012                 if (!str)
2013                     debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2014                 break;
2015             case CONF_CBK:
2016                 cbk = va_arg(ap, void (*)(FILE *, char *, char *, char *));
2017                 break;
2018             default:
2019                 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2020             }
2021             if (!strcasecmp(opt, word))
2022                 break;
2023         }
2024         va_end(ap);
2025         
2026         if (!word) {
2027             if (block)
2028                 debugx(1, DBG_ERR, "configuration error in block %s, unknown option %s", block, opt);
2029             debugx(1, DBG_ERR, "configuration error, unknown option %s", opt);
2030         }
2031
2032         if (type != conftype) {
2033             if (block)
2034                 debugx(1, DBG_ERR, "configuration error in block %s, wrong syntax for option %s", block, opt);
2035             debugx(1, DBG_ERR, "configuration error, wrong syntax for option %s", opt);
2036         }
2037         
2038         switch (type) {
2039         case CONF_STR:
2040             if (block)
2041                 debug(DBG_DBG, "getgeneralconfig: block %s: %s = %s", block, opt, val);
2042             else 
2043                 debug(DBG_DBG, "getgeneralconfig: %s = %s", opt, val);
2044             *str = stringcopy(val, 0);
2045             break;
2046         case CONF_CBK:
2047             optval = malloc(strlen(opt) + strlen(val) + 2);
2048             if (!optval)
2049                 debugx(1, DBG_ERR, "malloc failed");
2050             sprintf(optval, "%s %s", opt, val);
2051             cbk(f, optval, opt, val);
2052             free(optval);
2053             break;
2054         default:
2055             debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2056         }
2057     }
2058 }
2059
2060 void confclsrv_cb(FILE *f, char *block, char *opt, char *val) {
2061     char *type = NULL, *secret = NULL, *port = NULL, *tls = NULL, *statusserver = NULL;
2062     struct client *client = NULL;
2063     struct server *server = NULL;
2064     struct peer *peer;
2065     
2066     debug(DBG_DBG, "confclsrv_cb called for %s", block);
2067     
2068     if (!strcasecmp(opt, "client")) {
2069         getgeneralconfig(f, block,
2070                          "type", CONF_STR, &type,
2071                          "secret", CONF_STR, &secret,
2072                          "tls", CONF_STR, &tls,
2073                          NULL
2074                          );
2075         client_count++;
2076         clients = realloc(clients, client_count * sizeof(struct client));
2077         if (!clients)
2078             debugx(1, DBG_ERR, "malloc failed");
2079         client = clients + client_count - 1;
2080         memset(client, 0, sizeof(struct client));
2081         peer = &client->peer;
2082     } else {
2083         getgeneralconfig(f, block,
2084                          "type", CONF_STR, &type,
2085                          "secret", CONF_STR, &secret,
2086                          "port", CONF_STR, &port,
2087                          "tls", CONF_STR, &tls,
2088                          "StatusServer", CONF_STR, &statusserver,
2089                          NULL
2090                          );
2091         server_count++;
2092         servers = realloc(servers, server_count * sizeof(struct server));
2093         if (!servers)
2094             debugx(1, DBG_ERR, "malloc failed");
2095         server = servers + server_count - 1;
2096         memset(server, 0, sizeof(struct server));
2097         peer = &server->peer;
2098         peer->port = port;
2099         if (statusserver) {
2100             if (!strcasecmp(statusserver, "on"))
2101                 server->statusserver = 1;
2102             else if (strcasecmp(statusserver, "off"))
2103                 debugx(1, DBG_ERR, "error in block %s, StatusServer is %s, must be on or off", block, statusserver);
2104             free(statusserver);
2105         }
2106     }
2107     
2108     peer->host = stringcopy(val, 0);
2109     
2110     if (type && !strcasecmp(type, "udp")) {
2111         peer->type = 'U';
2112         if (client)
2113             client_udp_count++;
2114         else {
2115             server_udp_count++;
2116             if (!port)
2117                 peer->port = stringcopy(DEFAULT_UDP_PORT, 0);
2118         }
2119     } else if (type && !strcasecmp(type, "tls")) {
2120         if (client) {
2121             peer->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultclient", "default");
2122             client_tls_count++;
2123         } else {
2124             peer->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultserver", "default");
2125             server_tls_count++;
2126             if (!port)
2127                 peer->port = stringcopy(DEFAULT_TLS_PORT, 0);
2128         }
2129         if (!peer->ssl_ctx)
2130             debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2131         peer->type = 'T';
2132     } else
2133         debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2134     free(type);
2135     
2136     if (!resolvepeer(peer, 0))
2137         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", peer->host, peer->port);
2138     
2139     if (!secret) {
2140         if (peer->type == 'U')
2141             debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2142         peer->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2143     } else {
2144         peer->secret = secret;
2145     }
2146
2147     if (client) {
2148         if (peer->type == 'U')
2149             client->replyq = &udp_server_replyq;
2150         else {
2151             client->replyq = malloc(sizeof(struct replyq));
2152             if (!client->replyq)
2153                 debugx(1, DBG_ERR, "malloc failed");
2154             client->replyq->replies = calloc(MAX_REQUESTS, sizeof(struct reply));
2155             if (!client->replyq->replies)
2156                 debugx(1, DBG_ERR, "malloc failed");
2157             client->replyq->size = MAX_REQUESTS;
2158             client->replyq->count = 0;
2159             pthread_mutex_init(&client->replyq->count_mutex, NULL);
2160             pthread_cond_init(&client->replyq->count_cond, NULL);
2161         }
2162     } else {
2163         pthread_mutex_init(&server->lock, NULL);
2164         server->sock = -1;
2165         server->requests = calloc(MAX_REQUESTS, sizeof(struct request));
2166         if (!server->requests)
2167             debugx(1, DBG_ERR, "malloc failed");
2168         server->newrq = 0;
2169         pthread_mutex_init(&server->newrq_mutex, NULL);
2170         pthread_cond_init(&server->newrq_cond, NULL);
2171     }
2172 }
2173
2174 void confrealm_cb(FILE *f, char *block, char *opt, char *val) {
2175     char *server = NULL, *msg = NULL;
2176     
2177     debug(DBG_DBG, "confrealm_cb called for %s", block);
2178     
2179     getgeneralconfig(f, block,
2180                      "server", CONF_STR, &server,
2181                      "ReplyMessage", CONF_STR, &msg,
2182                      NULL
2183                      );
2184
2185     addrealm(val, server, msg);
2186     free(server);
2187 }
2188
2189 void conftls_cb(FILE *f, char *block, char *opt, char *val) {
2190     char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
2191     
2192     debug(DBG_DBG, "conftls_cb called for %s", block);
2193     
2194     getgeneralconfig(f, block,
2195                      "CACertificateFile", CONF_STR, &cacertfile,
2196                      "CACertificatePath", CONF_STR, &cacertpath,
2197                      "CertificateFile", CONF_STR, &certfile,
2198                      "CertificateKeyFile", CONF_STR, &certkeyfile,
2199                      "CertificateKeyPassword", CONF_STR, &certkeypwd,
2200                      NULL
2201                      );
2202     
2203     tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
2204     free(cacertfile);
2205     free(cacertpath);
2206     free(certfile);
2207     free(certkeyfile);
2208     free(certkeypwd);
2209 }
2210
2211 void getmainconfig(const char *configfile) {
2212     FILE *f;
2213     char *loglevel = NULL;
2214
2215     f = openconfigfile(configfile);
2216     memset(&options, 0, sizeof(options));
2217
2218     getgeneralconfig(f, NULL,
2219                      "ListenUDP", CONF_STR, &options.listenudp,
2220                      "ListenTCP", CONF_STR, &options.listentcp,
2221                      "LogLevel", CONF_STR, &loglevel,
2222                      "LogDestination", CONF_STR, &options.logdestination,
2223                      "Client", CONF_CBK, confclsrv_cb,
2224                      "Server", CONF_CBK, confclsrv_cb,
2225                      "Realm", CONF_CBK, confrealm_cb,
2226                      "TLS", CONF_CBK, conftls_cb,
2227                      NULL
2228                      );
2229     fclose(f);
2230     tlsfree();
2231     
2232     if (loglevel) {
2233         if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
2234             debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
2235         options.loglevel = *loglevel - '0';
2236         free(loglevel);
2237     }
2238
2239     if (client_udp_count) {
2240         udp_server_replyq.replies = malloc(client_udp_count * MAX_REQUESTS * sizeof(struct reply));
2241         if (!udp_server_replyq.replies)
2242             debugx(1, DBG_ERR, "malloc failed");
2243         udp_server_replyq.size = client_udp_count * MAX_REQUESTS;
2244         udp_server_replyq.count = 0;
2245         pthread_mutex_init(&udp_server_replyq.count_mutex, NULL);
2246         pthread_cond_init(&udp_server_replyq.count_cond, NULL);
2247     }    
2248 }
2249
2250 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *loglevel, char **configfile) {
2251     int c;
2252
2253     while ((c = getopt(argc, argv, "c:d:fv")) != -1) {
2254         switch (c) {
2255         case 'c':
2256             *configfile = optarg;
2257             break;
2258         case 'd':
2259             if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
2260                 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
2261             *loglevel = *optarg - '0';
2262             break;
2263         case 'f':
2264             *foreground = 1;
2265             break;
2266         case 'v':
2267                 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
2268         default:
2269             goto usage;
2270         }
2271     }
2272     if (!(argc - optind))
2273         return;
2274
2275  usage:
2276     debug(DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -v ]", argv[0]);
2277     exit(1);
2278 }
2279
2280 int main(int argc, char **argv) {
2281     pthread_t udpserverth;
2282     int i;
2283     uint8_t foreground = 0, loglevel = 0;
2284     char *configfile = NULL;
2285     
2286     debug_init("radsecproxy");
2287     debug_set_level(DEBUG_LEVEL);
2288     getargs(argc, argv, &foreground, &loglevel, &configfile);
2289     if (loglevel)
2290         debug_set_level(loglevel);
2291     debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
2292     getmainconfig(configfile ? configfile : CONFIG_MAIN);
2293     if (loglevel)
2294         options.loglevel = loglevel;
2295     else if (options.loglevel)
2296         debug_set_level(options.loglevel);
2297     if (foreground)
2298         options.logdestination = NULL;
2299     else {
2300         if (!options.logdestination)
2301             options.logdestination = "x-syslog:///";
2302         debug_set_destination(options.logdestination);
2303     }
2304
2305     if (!server_count)
2306         debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
2307     if (!client_count)
2308         debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
2309     if (!realm_count)
2310         debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
2311
2312     if (!foreground && (daemon(0, 0) < 0))
2313         debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
2314         
2315     if (client_udp_count) {
2316         udp_server_listen = server_create('U');
2317         if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
2318             debugx(1, DBG_ERR, "pthread_create failed");
2319     }
2320     
2321     for (i = 0; i < server_count; i++)
2322         if (pthread_create(&servers[i].clientth, NULL, clientwr, (void *)&servers[i]))
2323             debugx(1, DBG_ERR, "pthread_create failed");
2324
2325     if (client_tls_count) {
2326         tcp_server_listen = server_create('T');
2327         return tlslistener();
2328     }
2329     
2330     /* just hang around doing nothing, anything to do here? */
2331     for (;;)
2332         sleep(1000);
2333 }