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