cff3e069c37e7931ca3e5dc77be2c3bdbe3e0a5f
[libradsec.git] / radsecproxy.c
1 /*
2  * Copyright (C) 2006-2008 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 #ifdef SYS_SOLARIS9
38 #include <fcntl.h>
39 #endif
40 #include <sys/time.h>
41 #include <sys/types.h>
42 #include <arpa/inet.h>
43 #include <regex.h>
44 #include <libgen.h>
45 #include <pthread.h>
46 #include <openssl/ssl.h>
47 #include <openssl/rand.h>
48 #include <openssl/err.h>
49 #include <openssl/md5.h>
50 #include <openssl/hmac.h>
51 #include <openssl/x509v3.h>
52 #include "debug.h"
53 #include "list.h"
54 #include "util.h"
55 #include "gconfig.h"
56 #include "radsecproxy.h"
57
58 static struct options options;
59 struct list *clconfs, *srvconfs, *realms, *tlsconfs, *rewriteconfs;
60
61 static int client_udp_count = 0;
62 static int client_tls_count = 0;
63 static int server_udp_count = 0;
64 static int server_tls_count = 0;
65
66 static struct clsrvconf *srcudpres = NULL;
67 static struct clsrvconf *srctcpres = NULL;
68
69 static struct replyq *udp_server_replyq = NULL;
70 static int udp_server_sock = -1;
71 static int udp_accserver_sock = -1;
72 static int udp_client4_sock = -1;
73 static int udp_client6_sock = -1;
74 static pthread_mutex_t *ssl_locks;
75 static long *ssl_lock_count;
76 extern int optind;
77 extern char *optarg;
78
79 /* callbacks for making OpenSSL thread safe */
80 unsigned long ssl_thread_id() {
81         return (unsigned long)pthread_self();
82 }
83
84 void ssl_locking_callback(int mode, int type, const char *file, int line) {
85     if (mode & CRYPTO_LOCK) {
86         pthread_mutex_lock(&ssl_locks[type]);
87         ssl_lock_count[type]++;
88     } else
89         pthread_mutex_unlock(&ssl_locks[type]);
90 }
91
92 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
93     int pwdlen = strlen(userdata);
94     if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
95         return 0;
96     memcpy(buf, userdata, pwdlen);
97     return pwdlen;
98 }
99
100 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
101   char buf[256];
102   X509 *err_cert;
103   int err, depth;
104
105   err_cert = X509_STORE_CTX_get_current_cert(ctx);
106   err = X509_STORE_CTX_get_error(ctx);
107   depth = X509_STORE_CTX_get_error_depth(ctx);
108
109   if (depth > MAX_CERT_DEPTH) {
110       ok = 0;
111       err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
112       X509_STORE_CTX_set_error(ctx, err);
113   }
114
115   if (!ok) {
116       X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
117       debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
118
119       switch (err) {
120       case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
121           X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
122           debug(DBG_WARN, "\tIssuer=%s", buf);
123           break;
124       case X509_V_ERR_CERT_NOT_YET_VALID:
125       case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
126           debug(DBG_WARN, "\tCertificate not yet valid");
127           break;
128       case X509_V_ERR_CERT_HAS_EXPIRED:
129           debug(DBG_WARN, "Certificate has expired");
130           break;
131       case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
132           debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
133           break;
134       }
135   }
136 #ifdef DEBUG  
137   printf("certificate verify returns %d\n", ok);
138 #endif  
139   return ok;
140 }
141
142 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
143     struct addrinfo hints, *addrinfo, *res;
144     char *slash, *s;
145     int plen;
146
147     slash = conf->host ? strchr(conf->host, '/') : NULL;
148     if (slash) {
149         s = slash + 1;
150         if (!*s) {
151             debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
152             return 0;
153         }
154         for (; *s; s++)
155             if (*s < '0' || *s > '9') {
156                 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
157                 return 0;
158             }
159         plen = atoi(slash + 1);
160         if (plen < 0 || plen > 128) {
161             debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
162             return 0;
163         }
164         *slash = '\0';
165     }
166     memset(&hints, 0, sizeof(hints));
167     hints.ai_socktype = (conf->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
168     hints.ai_family = AF_UNSPEC;
169     hints.ai_flags = ai_flags;
170     if (!conf->host && !conf->port) {
171         /* getaddrinfo() doesn't like host and port to be NULL */
172         if (getaddrinfo(conf->host, DEFAULT_UDP_PORT, &hints, &addrinfo)) {
173             debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
174             return 0;
175         }
176         for (res = addrinfo; res; res = res->ai_next) {
177             switch (res->ai_family) {
178             case AF_INET:
179                 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
180                 break;
181             case AF_INET6:
182                 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
183                 break;
184             }
185         }
186     } else {
187         if (slash)
188             hints.ai_flags |= AI_NUMERICHOST;
189         if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
190             debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
191             return 0;
192         }
193         if (slash) {
194             *slash = '/';
195             switch (addrinfo->ai_family) {
196             case AF_INET:
197                 if (plen > 32) {
198                     debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
199                     freeaddrinfo(addrinfo);
200                     return 0;
201                 }
202                 break;
203             case AF_INET6:
204                 break;
205             default:
206                 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
207                 freeaddrinfo(addrinfo);
208                 return 0;
209             }
210             conf->prefixlen = plen;
211         } else
212             conf->prefixlen = 255;
213     }
214     if (conf->addrinfo)
215         freeaddrinfo(conf->addrinfo);
216     conf->addrinfo = addrinfo;
217     return 1;
218 }         
219
220 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
221     int s, on = 1;
222     struct addrinfo *res;
223     
224     for (res = addrinfo; res; res = res->ai_next) {
225         if (family != AF_UNSPEC && family != res->ai_family)
226             continue;
227         s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
228         if (s < 0) {
229             debug(DBG_WARN, "bindtoaddr: socket failed");
230             continue;
231         }
232         if (reuse)
233             setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
234 #ifdef IPV6_V6ONLY
235         if (v6only)
236             setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
237 #endif          
238
239         if (!bind(s, res->ai_addr, res->ai_addrlen))
240             return s;
241         debug(DBG_WARN, "bindtoaddr: bind failed");
242         close(s);
243     }
244     return -1;
245 }         
246
247 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
248     char *p, *field;
249     int ipv6 = 0;
250
251     p = s;
252     /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
253     if (*p == '[') {
254         p++;
255         field = p;
256         for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
257         if (*p != ']')
258             debugx(1, DBG_ERR, "no ] matching initial [");
259         ipv6 = 1;
260     } else {
261         field = p;
262         for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
263     }
264     if (field == p)
265         debugx(1, DBG_ERR, "missing host/address");
266
267     conf->host = stringcopy(field, p - field);
268     if (ipv6) {
269         p++;
270         if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
271             debugx(1, DBG_ERR, "unexpected character after ]");
272     }
273     if (*p == ':') {
274             /* port number or service name is specified */;
275             field = ++p;
276             for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
277             if (field == p)
278                 debugx(1, DBG_ERR, "syntax error, : but no following port");
279             conf->port = stringcopy(field, p - field);
280     } else
281         conf->port = default_port ? stringcopy(default_port, 0) : NULL;
282     return p;
283 }
284
285 struct clsrvconf *resolve_hostport(char type, char *lconf, char *default_port) {
286     struct clsrvconf *conf;
287
288     conf = malloc(sizeof(struct clsrvconf));
289     if (!conf)
290         debugx(1, DBG_ERR, "malloc failed");
291     memset(conf, 0, sizeof(struct clsrvconf));
292     conf->type = type;
293     if (lconf) {
294         parsehostport(lconf, conf, default_port);
295         if (!strcmp(conf->host, "*")) {
296             free(conf->host);
297             conf->host = NULL;
298         }
299     } else
300         conf->port = default_port ? stringcopy(default_port, 0) : NULL;
301     if (!resolvepeer(conf, AI_PASSIVE))
302         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
303     return conf;
304 }
305
306 int connecttcp(struct addrinfo *addrinfo) {
307     int s;
308     struct addrinfo *res;
309
310     s = -1;
311     for (res = addrinfo; res; res = res->ai_next) {
312         s = bindtoaddr(srctcpres->addrinfo, res->ai_family, 1, 1);
313         if (s < 0) {
314             debug(DBG_WARN, "connecttoserver: socket failed");
315             continue;
316         }
317         if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
318             break;
319         debug(DBG_WARN, "connecttoserver: connect failed");
320         close(s);
321         s = -1;
322     }
323     return s;
324 }         
325
326 /* returns 1 if the len first bits are equal, else 0 */
327 int prefixmatch(void *a1, void *a2, uint8_t len) {
328     static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
329     int r, l = len / 8;
330     if (l && memcmp(a1, a2, l))
331         return 0;
332     r = len % 8;
333     if (!r)
334         return 1;
335     return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
336 }
337
338 /* returns the config with matching address, or NULL */
339 /* if conf argument is not NULL, we only check that one */
340 struct clsrvconf *find_conf(char type, struct sockaddr *addr, struct list *confs, struct clsrvconf *conf) {
341     struct sockaddr_in6 *sa6 = NULL;
342     struct in_addr *a4 = NULL;
343     struct addrinfo *res;
344     struct list_node *entry;
345     
346     if (addr->sa_family == AF_INET6) {
347         sa6 = (struct sockaddr_in6 *)addr;
348         if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
349             a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
350             sa6 = NULL;
351         }
352     } else
353         a4 = &((struct sockaddr_in *)addr)->sin_addr;
354
355     if (conf) {
356         if (conf->type == type) {
357             if (conf->prefixlen == 255) {
358                 for (res = conf->addrinfo; res; res = res->ai_next)
359                     if ((a4 && res->ai_family == AF_INET &&
360                          !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
361                         (sa6 && res->ai_family == AF_INET6 &&
362                          !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
363                         return conf;
364             } else {
365                 res = conf->addrinfo;
366                 if (res &&
367                     ((a4 && res->ai_family == AF_INET &&
368                       prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
369                      (sa6 && res->ai_family == AF_INET6 &&
370                       prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
371                     return conf;
372             }
373         }
374         return NULL;
375     }
376
377     for (entry = list_first(confs); entry; entry = list_next(entry)) {  
378         conf = (struct clsrvconf *)entry->data;
379         if (conf->type == type) {
380             if (conf->prefixlen == 255) {
381                 for (res = conf->addrinfo; res; res = res->ai_next)
382                     if ((a4 && res->ai_family == AF_INET &&
383                          !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
384                         (sa6 && res->ai_family == AF_INET6 &&
385                          !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
386                         return conf;
387             } else {
388                 res = conf->addrinfo;
389                 if (res &&
390                     ((a4 && res->ai_family == AF_INET &&
391                       prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
392                      (sa6 && res->ai_family == AF_INET6 &&
393                       prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
394                     return conf;
395             }
396         }
397     }    
398     return NULL;
399 }
400
401 struct replyq *newreplyq() {
402     struct replyq *replyq;
403     
404     replyq = malloc(sizeof(struct replyq));
405     if (!replyq)
406         debugx(1, DBG_ERR, "malloc failed");
407     replyq->replies = list_create();
408     if (!replyq->replies)
409         debugx(1, DBG_ERR, "malloc failed");
410     pthread_mutex_init(&replyq->mutex, NULL);
411     pthread_cond_init(&replyq->cond, NULL);
412     return replyq;
413 }
414
415 struct client *addclient(struct clsrvconf *conf) {
416     struct client *new = malloc(sizeof(struct client));
417     
418     if (!new) {
419         debug(DBG_ERR, "malloc failed");
420         return NULL;
421     }
422     if (!conf->clients) {
423         conf->clients = list_create();
424         if (!conf->clients) {
425             debug(DBG_ERR, "malloc failed");
426             return NULL;
427         }
428     }
429     
430     memset(new, 0, sizeof(struct client));
431     new->conf = conf;
432     new->replyq = conf->type == 'T' ? newreplyq() : udp_server_replyq;
433
434     list_push(conf->clients, new);
435     return new;
436 }
437
438 void removeclient(struct client *client) {
439     if (!client || !client->conf->clients)
440         return;
441
442     list_removedata(client->conf->clients, client);
443     free(client);
444 }
445
446 void addserver(struct clsrvconf *conf) {
447     if (conf->servers)
448         debugx(1, DBG_ERR, "addserver: currently works with just one server per conf");
449     
450     conf->servers = malloc(sizeof(struct server));
451     if (!conf->servers)
452         debugx(1, DBG_ERR, "malloc failed");
453     memset(conf->servers, 0, sizeof(struct server));
454     conf->servers->conf = conf;
455
456     if (conf->type == 'U') {
457         if (!srcudpres)
458             srcudpres = resolve_hostport('U', options.sourceudp, NULL);
459         switch (conf->addrinfo->ai_family) {
460         case AF_INET:
461             if (udp_client4_sock < 0) {
462                 udp_client4_sock = bindtoaddr(srcudpres->addrinfo, AF_INET, 0, 1);
463                 if (udp_client4_sock < 0)
464                     debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
465             }
466             conf->servers->sock = udp_client4_sock;
467             break;
468         case AF_INET6:
469             if (udp_client6_sock < 0) {
470                 udp_client6_sock = bindtoaddr(srcudpres->addrinfo, AF_INET6, 0, 1);
471                 if (udp_client6_sock < 0)
472                     debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
473             }
474             conf->servers->sock = udp_client6_sock;
475             break;
476         default:
477             debugx(1, DBG_ERR, "addserver: unsupported address family");
478         }
479         
480     } else {
481         if (!srctcpres)
482             srctcpres = resolve_hostport('T', options.sourcetcp, NULL);
483         conf->servers->sock = -1;
484     }
485     
486     pthread_mutex_init(&conf->servers->lock, NULL);
487     conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
488     if (!conf->servers->requests)
489         debugx(1, DBG_ERR, "malloc failed");
490     conf->servers->newrq = 0;
491     pthread_mutex_init(&conf->servers->newrq_mutex, NULL);
492     pthread_cond_init(&conf->servers->newrq_cond, NULL);
493 }
494
495 /* exactly one of client and server must be non-NULL */
496 /* should probably take peer list (client(s) or server(s)) as argument instead */
497 /* if *peer == NULL we return who we received from, else require it to be from peer */
498 /* return from in sa if not NULL */
499 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
500     int cnt, len;
501     unsigned char buf[65536], *rad;
502     struct sockaddr_storage from;
503     socklen_t fromlen = sizeof(from);
504     struct clsrvconf *p;
505     struct list_node *node;
506     
507     for (;;) {
508         cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
509         if (cnt == -1) {
510             debug(DBG_WARN, "radudpget: recv failed");
511             continue;
512         }
513         debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
514
515         if (cnt < 20) {
516             debug(DBG_WARN, "radudpget: packet too small");
517             continue;
518         }
519     
520         len = RADLEN(buf);
521         if (len < 20) {
522             debug(DBG_WARN, "radudpget: length too small");
523             continue;
524         }
525
526         if (cnt < len) {
527             debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
528             continue;
529         }
530         if (cnt > len)
531             debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
532
533         if (client)
534             if (*client)
535                 p = find_conf('U', (struct sockaddr *)&from, NULL, (*client)->conf);
536             else
537                 p = find_conf('U', (struct sockaddr *)&from, clconfs, NULL);
538         else
539             if (*server)
540                 p = find_conf('U', (struct sockaddr *)&from, NULL, (*server)->conf);
541             else
542                 p = find_conf('U', (struct sockaddr *)&from, srvconfs, NULL);
543
544         if (!p) {
545             debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer, ignoring");
546             continue;
547         }
548         
549         rad = malloc(len);
550         if (!rad) {
551             debug(DBG_ERR, "radudpget: malloc failed");
552             continue;
553         }
554         
555         if (client && !*client) {
556             node = list_first(p->clients);
557             *client = node ? (struct client *)node->data : addclient(p);
558             if (!*client) {
559                 free(rad);
560                 continue;
561             }
562         } else if (server && !*server)
563             *server = p->servers;
564         
565         break;
566     }
567     memcpy(rad, buf, len);
568     if (sa)
569         *sa = from;
570     return rad;
571 }
572
573 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
574     int loc, i, l, n, r = 0;
575     char *v;
576     X509_EXTENSION *ex;
577     STACK_OF(GENERAL_NAME) *alt;
578     GENERAL_NAME *gn;
579     
580     debug(DBG_DBG, "subjectaltnameaddr");
581     
582     loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
583     if (loc < 0)
584         return r;
585     
586     ex = X509_get_ext(cert, loc);
587     alt = X509V3_EXT_d2i(ex);
588     if (!alt)
589         return r;
590     
591     n = sk_GENERAL_NAME_num(alt);
592     for (i = 0; i < n; i++) {
593         gn = sk_GENERAL_NAME_value(alt, i);
594         if (gn->type != GEN_IPADD)
595             continue;
596         r = -1;
597         v = (char *)ASN1_STRING_data(gn->d.ia5);
598         l = ASN1_STRING_length(gn->d.ia5);
599         if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
600             && !memcmp(v, &addr, l)) {
601             r = 1;
602             break;
603         }
604     }
605     GENERAL_NAMES_free(alt);
606     return r;
607 }
608
609 int subjectaltnameregexp(X509 *cert, int type, char *exact,  regex_t *regex) {
610     int loc, i, l, n, r = 0;
611     char *s, *v;
612     X509_EXTENSION *ex;
613     STACK_OF(GENERAL_NAME) *alt;
614     GENERAL_NAME *gn;
615     
616     debug(DBG_DBG, "subjectaltnameregexp");
617     
618     loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
619     if (loc < 0)
620         return r;
621     
622     ex = X509_get_ext(cert, loc);
623     alt = X509V3_EXT_d2i(ex);
624     if (!alt)
625         return r;
626     
627     n = sk_GENERAL_NAME_num(alt);
628     for (i = 0; i < n; i++) {
629         gn = sk_GENERAL_NAME_value(alt, i);
630         if (gn->type != type)
631             continue;
632         r = -1;
633         v = (char *)ASN1_STRING_data(gn->d.ia5);
634         l = ASN1_STRING_length(gn->d.ia5);
635         if (l <= 0)
636             continue;
637 #ifdef DEBUG
638         printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
639 #endif  
640         if (exact) {
641             if (memcmp(v, exact, l))
642                 continue;
643         } else {
644             s = stringcopy((char *)v, l);
645             if (!s) {
646                 debug(DBG_ERR, "malloc failed");
647                 continue;
648             }
649             if (regexec(regex, s, 0, NULL, 0)) {
650                 free(s);
651                 continue;
652             }
653             free(s);
654         }
655         r = 1;
656         break;
657     }
658     GENERAL_NAMES_free(alt);
659     return r;
660 }
661
662 int tlsverifycert(SSL *ssl, struct clsrvconf *conf) {
663     int l, loc, r;
664     X509 *cert;
665     X509_NAME *nm;
666     X509_NAME_ENTRY *e;
667     ASN1_STRING *s;
668     char *v;
669     uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
670     unsigned long error;
671     struct in6_addr addr;
672     
673     if (SSL_get_verify_result(ssl) != X509_V_OK) {
674         debug(DBG_ERR, "tlsverifycert: basic validation failed");
675         while ((error = ERR_get_error()))
676             debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
677         return 0;
678     }
679
680     cert = SSL_get_peer_certificate(ssl);
681     if (!cert) {
682         debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
683         return 0;
684     }
685
686     if (conf->prefixlen == 255) {
687         if (inet_pton(AF_INET, conf->host, &addr))
688             type = AF_INET;
689         else if (inet_pton(AF_INET6, conf->host, &addr))
690             type = AF_INET6;
691
692         r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
693         if (r) {
694             if (r < 0) {
695                 X509_free(cert);
696                 debug(DBG_DBG, "tlsverifycert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
697                 return 0;
698             }
699             debug(DBG_DBG, "tlsverifycert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
700         } else {
701             nm = X509_get_subject_name(cert);
702             loc = -1;
703             for (;;) {
704                 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
705                 if (loc == -1)
706                     break;
707                 e = X509_NAME_get_entry(nm, loc);
708                 s = X509_NAME_ENTRY_get_data(e);
709                 v = (char *) ASN1_STRING_data(s);
710                 l = ASN1_STRING_length(s);
711                 if (l < 0)
712                     continue;
713 #ifdef DEBUG
714                 printfchars(NULL, "cn", NULL, v, l);
715 #endif      
716                 if (l == strlen(conf->host) && !strncasecmp(conf->host, v, l)) {
717                     r = 1;
718                     debug(DBG_DBG, "tlsverifycert: Found cn matching host %s", conf->host);
719                     break;
720                 }
721             }
722             if (!r) {
723                 X509_free(cert);
724                 debug(DBG_ERR, "tlsverifycert: cn not matching host %s", conf->host);
725                 return 0;
726             }
727         }
728     }
729     if (conf->certuriregex) {
730         r = subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex);
731         if (r < 1) {
732             debug(DBG_DBG, "tlsverifycert: subjectaltname URI not matching regex");
733             X509_free(cert);
734             return 0;
735         }
736         debug(DBG_DBG, "tlsverifycert: subjectaltname URI matching regex");
737     }
738     X509_free(cert);
739     return 1;
740 }
741
742 void tlsconnect(struct server *server, struct timeval *when, char *text) {
743     struct timeval now;
744     time_t elapsed;
745
746     debug(DBG_DBG, "tlsconnect called from %s", text);
747     pthread_mutex_lock(&server->lock);
748     if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
749         /* already reconnected, nothing to do */
750         debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
751         pthread_mutex_unlock(&server->lock);
752         return;
753     }
754
755     debug(DBG_DBG, "tlsconnect %s", text);
756
757     for (;;) {
758         gettimeofday(&now, NULL);
759         elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
760         if (server->connectionok) {
761             server->connectionok = 0;
762             sleep(10);
763         } else if (elapsed < 5)
764             sleep(10);
765         else if (elapsed < 300) {
766             debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
767             sleep(elapsed);
768         } else if (elapsed < 100000) {
769             debug(DBG_INFO, "tlsconnect: sleeping %ds", 600);
770             sleep(600);
771         } else
772             server->lastconnecttry.tv_sec = now.tv_sec;  /* no sleep at startup */
773         debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
774         if (server->sock >= 0)
775             close(server->sock);
776         if ((server->sock = connecttcp(server->conf->addrinfo)) < 0) {
777             debug(DBG_ERR, "tlsconnect: connecttcp failed");
778             continue;
779         }
780         
781         SSL_free(server->ssl);
782         server->ssl = SSL_new(server->conf->ssl_ctx);
783         SSL_set_fd(server->ssl, server->sock);
784         if (SSL_connect(server->ssl) > 0 && tlsverifycert(server->ssl, server->conf))
785             break;
786     }
787     debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
788     gettimeofday(&server->lastconnecttry, NULL);
789     pthread_mutex_unlock(&server->lock);
790 }
791
792 unsigned char *radtlsget(SSL *ssl) {
793     int cnt, total, len;
794     unsigned char buf[4], *rad;
795
796     for (;;) {
797         for (total = 0; total < 4; total += cnt) {
798             cnt = SSL_read(ssl, buf + total, 4 - total);
799             if (cnt <= 0) {
800                 debug(DBG_ERR, "radtlsget: connection lost");
801                 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
802                     /* remote end sent close_notify, send one back */
803                     SSL_shutdown(ssl);
804                 }
805                 return NULL;
806             }
807         }
808
809         len = RADLEN(buf);
810         rad = malloc(len);
811         if (!rad) {
812             debug(DBG_ERR, "radtlsget: malloc failed");
813             continue;
814         }
815         memcpy(rad, buf, 4);
816
817         for (; total < len; total += cnt) {
818             cnt = SSL_read(ssl, rad + total, len - total);
819             if (cnt <= 0) {
820                 debug(DBG_ERR, "radtlsget: connection lost");
821                 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
822                     /* remote end sent close_notify, send one back */
823                     SSL_shutdown(ssl);
824                 }
825                 free(rad);
826                 return NULL;
827             }
828         }
829     
830         if (total >= 20)
831             break;
832         
833         free(rad);
834         debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
835     }
836     
837     debug(DBG_DBG, "radtlsget: got %d bytes", total);
838     return rad;
839 }
840
841 int clientradput(struct server *server, unsigned char *rad) {
842     int cnt;
843     size_t len;
844     unsigned long error;
845     struct timeval lastconnecttry;
846     struct clsrvconf *conf = server->conf;
847     
848     len = RADLEN(rad);
849     if (conf->type == 'U') {
850         if (sendto(server->sock, rad, len, 0, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen) >= 0) {
851             debug(DBG_DBG, "clienradput: sent UDP of length %d to %s port %s", len, conf->host, conf->port);
852             return 1;
853         }
854         debug(DBG_WARN, "clientradput: send failed");
855         return 0;
856     }
857
858     lastconnecttry = server->lastconnecttry;
859     while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
860         while ((error = ERR_get_error()))
861             debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
862         tlsconnect(server, &lastconnecttry, "clientradput");
863         lastconnecttry = server->lastconnecttry;
864     }
865
866     server->connectionok = 1;
867     debug(DBG_DBG, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
868     return 1;
869 }
870
871 int radsign(unsigned char *rad, unsigned char *sec) {
872     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
873     static unsigned char first = 1;
874     static EVP_MD_CTX mdctx;
875     unsigned int md_len;
876     int result;
877     
878     pthread_mutex_lock(&lock);
879     if (first) {
880         EVP_MD_CTX_init(&mdctx);
881         first = 0;
882     }
883
884     result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
885         EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
886         EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
887         EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
888         md_len == 16);
889     pthread_mutex_unlock(&lock);
890     return result;
891 }
892
893 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
894     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
895     static unsigned char first = 1;
896     static EVP_MD_CTX mdctx;
897     unsigned char hash[EVP_MAX_MD_SIZE];
898     unsigned int len;
899     int result;
900     
901     pthread_mutex_lock(&lock);
902     if (first) {
903         EVP_MD_CTX_init(&mdctx);
904         first = 0;
905     }
906
907     len = RADLEN(rad);
908     
909     result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
910               EVP_DigestUpdate(&mdctx, rad, 4) &&
911               EVP_DigestUpdate(&mdctx, reqauth, 16) &&
912               (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
913               EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
914               EVP_DigestFinal_ex(&mdctx, hash, &len) &&
915               len == 16 &&
916               !memcmp(hash, rad + 4, 16));
917     pthread_mutex_unlock(&lock);
918     return result;
919 }
920               
921 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
922     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
923     static unsigned char first = 1;
924     static HMAC_CTX hmacctx;
925     unsigned int md_len;
926     uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
927     
928     pthread_mutex_lock(&lock);
929     if (first) {
930         HMAC_CTX_init(&hmacctx);
931         first = 0;
932     }
933
934     memcpy(auth, authattr, 16);
935     memset(authattr, 0, 16);
936     md_len = 0;
937     HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
938     HMAC_Update(&hmacctx, rad, RADLEN(rad));
939     HMAC_Final(&hmacctx, hash, &md_len);
940     memcpy(authattr, auth, 16);
941     if (md_len != 16) {
942         debug(DBG_WARN, "message auth computation failed");
943         pthread_mutex_unlock(&lock);
944         return 0;
945     }
946
947     if (memcmp(auth, hash, 16)) {
948         debug(DBG_WARN, "message authenticator, wrong value");
949         pthread_mutex_unlock(&lock);
950         return 0;
951     }   
952         
953     pthread_mutex_unlock(&lock);
954     return 1;
955 }
956
957 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
958     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
959     static unsigned char first = 1;
960     static HMAC_CTX hmacctx;
961     unsigned int md_len;
962
963     if (!authattrval)
964         return 1;
965     
966     pthread_mutex_lock(&lock);
967     if (first) {
968         HMAC_CTX_init(&hmacctx);
969         first = 0;
970     }
971
972     memset(authattrval, 0, 16);
973     md_len = 0;
974     HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
975     HMAC_Update(&hmacctx, rad, RADLEN(rad));
976     HMAC_Final(&hmacctx, authattrval, &md_len);
977     if (md_len != 16) {
978         debug(DBG_WARN, "message auth computation failed");
979         pthread_mutex_unlock(&lock);
980         return 0;
981     }
982
983     pthread_mutex_unlock(&lock);
984     return 1;
985 }
986
987 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
988     while (length > 1) {
989         if (ATTRTYPE(attrs) == type)
990             return attrs;
991         length -= ATTRLEN(attrs);
992         attrs += ATTRLEN(attrs);
993     }
994     return NULL;
995 }
996
997 void freerqdata(struct request *rq) {
998     if (rq->origusername)
999         free(rq->origusername);
1000     if (rq->buf)
1001         free(rq->buf);
1002 }
1003
1004 void sendrq(struct server *to, struct request *rq) {
1005     int i;
1006     uint8_t *attr;
1007
1008     pthread_mutex_lock(&to->newrq_mutex);
1009     /* might simplify if only try nextid, might be ok */
1010     for (i = to->nextid; i < MAX_REQUESTS; i++)
1011         if (!to->requests[i].buf)
1012             break;
1013     if (i == MAX_REQUESTS) {
1014         for (i = 0; i < to->nextid; i++)
1015             if (!to->requests[i].buf)
1016                 break;
1017         if (i == to->nextid) {
1018             debug(DBG_WARN, "No room in queue, dropping request");
1019             freerqdata(rq);
1020             pthread_mutex_unlock(&to->newrq_mutex);
1021             return;
1022         }
1023     }
1024     
1025     rq->buf[1] = (char)i;
1026
1027     attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1028     if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1029         freerqdata(rq);
1030         pthread_mutex_unlock(&to->newrq_mutex);
1031         return;
1032     }
1033
1034     debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1035     to->requests[i] = *rq;
1036     to->nextid = i + 1;
1037
1038     if (!to->newrq) {
1039         to->newrq = 1;
1040         debug(DBG_DBG, "signalling client writer");
1041         pthread_cond_signal(&to->newrq_cond);
1042     }
1043     pthread_mutex_unlock(&to->newrq_mutex);
1044 }
1045
1046 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
1047     struct reply *reply;
1048     uint8_t first;
1049     
1050     if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1051         free(buf);
1052         debug(DBG_WARN, "sendreply: failed to sign message");
1053         return;
1054     }
1055
1056     reply = malloc(sizeof(struct reply));
1057     if (!reply) {
1058         free(buf);
1059         debug(DBG_ERR, "sendreply: malloc failed");
1060         return;
1061     }
1062     memset(reply, 0, sizeof(struct reply));
1063     reply->buf = buf;
1064     if (tosa)
1065         reply->tosa = *tosa;
1066     
1067     pthread_mutex_lock(&to->replyq->mutex);
1068
1069     first = list_first(to->replyq->replies) == NULL;
1070     
1071     if (!list_push(to->replyq->replies, reply)) {
1072         pthread_mutex_unlock(&to->replyq->mutex);
1073         free(reply);
1074         free(buf);
1075         debug(DBG_ERR, "sendreply: malloc failed");
1076         return;
1077     }
1078     
1079     if (first) {
1080         debug(DBG_DBG, "signalling server writer");
1081         pthread_cond_signal(&to->replyq->cond);
1082     }
1083     pthread_mutex_unlock(&to->replyq->mutex);
1084 }
1085
1086 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1087     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1088     static unsigned char first = 1;
1089     static EVP_MD_CTX mdctx;
1090     unsigned char hash[EVP_MAX_MD_SIZE], *input;
1091     unsigned int md_len;
1092     uint8_t i, offset = 0, out[128];
1093     
1094     pthread_mutex_lock(&lock);
1095     if (first) {
1096         EVP_MD_CTX_init(&mdctx);
1097         first = 0;
1098     }
1099
1100     input = auth;
1101     for (;;) {
1102         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1103             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1104             !EVP_DigestUpdate(&mdctx, input, 16) ||
1105             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1106             md_len != 16) {
1107             pthread_mutex_unlock(&lock);
1108             return 0;
1109         }
1110         for (i = 0; i < 16; i++)
1111             out[offset + i] = hash[i] ^ in[offset + i];
1112         input = out + offset - 16;
1113         offset += 16;
1114         if (offset == len)
1115             break;
1116     }
1117     memcpy(in, out, len);
1118     pthread_mutex_unlock(&lock);
1119     return 1;
1120 }
1121
1122 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1123     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1124     static unsigned char first = 1;
1125     static EVP_MD_CTX mdctx;
1126     unsigned char hash[EVP_MAX_MD_SIZE], *input;
1127     unsigned int md_len;
1128     uint8_t i, offset = 0, out[128];
1129     
1130     pthread_mutex_lock(&lock);
1131     if (first) {
1132         EVP_MD_CTX_init(&mdctx);
1133         first = 0;
1134     }
1135
1136     input = auth;
1137     for (;;) {
1138         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1139             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1140             !EVP_DigestUpdate(&mdctx, input, 16) ||
1141             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1142             md_len != 16) {
1143             pthread_mutex_unlock(&lock);
1144             return 0;
1145         }
1146         for (i = 0; i < 16; i++)
1147             out[offset + i] = hash[i] ^ in[offset + i];
1148         input = in + offset;
1149         offset += 16;
1150         if (offset == len)
1151             break;
1152     }
1153     memcpy(in, out, len);
1154     pthread_mutex_unlock(&lock);
1155     return 1;
1156 }
1157
1158 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1159     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1160     static unsigned char first = 1;
1161     static EVP_MD_CTX mdctx;
1162     unsigned char hash[EVP_MAX_MD_SIZE];
1163     unsigned int md_len;
1164     uint8_t i, offset;
1165     
1166     pthread_mutex_lock(&lock);
1167     if (first) {
1168         EVP_MD_CTX_init(&mdctx);
1169         first = 0;
1170     }
1171
1172 #if 0
1173     printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1174     printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1175     printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1176 #endif
1177     
1178     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1179         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1180         !EVP_DigestUpdate(&mdctx, auth, 16) ||
1181         !EVP_DigestUpdate(&mdctx, salt, 2) ||
1182         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1183         pthread_mutex_unlock(&lock);
1184         return 0;
1185     }
1186
1187 #if 0    
1188     printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1189 #endif
1190     
1191     for (i = 0; i < 16; i++)
1192         text[i] ^= hash[i];
1193     
1194     for (offset = 16; offset < len; offset += 16) {
1195 #if 0   
1196         printf("text + offset - 16 c(%d): ", offset / 16);
1197         printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1198 #endif
1199         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1200             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1201             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1202             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1203             md_len != 16) {
1204             pthread_mutex_unlock(&lock);
1205             return 0;
1206         }
1207 #if 0
1208         printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1209 #endif    
1210         
1211         for (i = 0; i < 16; i++)
1212             text[offset + i] ^= hash[i];
1213     }
1214     
1215 #if 0
1216     printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1217 #endif
1218
1219     pthread_mutex_unlock(&lock);
1220     return 1;
1221 }
1222
1223 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1224     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1225     static unsigned char first = 1;
1226     static EVP_MD_CTX mdctx;
1227     unsigned char hash[EVP_MAX_MD_SIZE];
1228     unsigned int md_len;
1229     uint8_t i, offset;
1230     char plain[255];
1231     
1232     pthread_mutex_lock(&lock);
1233     if (first) {
1234         EVP_MD_CTX_init(&mdctx);
1235         first = 0;
1236     }
1237
1238 #if 0
1239     printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1240     printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1241     printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1242 #endif
1243     
1244     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1245         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1246         !EVP_DigestUpdate(&mdctx, auth, 16) ||
1247         !EVP_DigestUpdate(&mdctx, salt, 2) ||
1248         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1249         pthread_mutex_unlock(&lock);
1250         return 0;
1251     }
1252
1253 #if 0    
1254     printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1255 #endif
1256     
1257     for (i = 0; i < 16; i++)
1258         plain[i] = text[i] ^ hash[i];
1259     
1260     for (offset = 16; offset < len; offset += 16) {
1261 #if 0   
1262         printf("text + offset - 16 c(%d): ", offset / 16);
1263         printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1264 #endif
1265         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1266             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1267             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1268             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1269             md_len != 16) {
1270             pthread_mutex_unlock(&lock);
1271             return 0;
1272         }
1273 #if 0
1274         printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1275 #endif    
1276
1277         for (i = 0; i < 16; i++)
1278             plain[offset + i] = text[offset + i] ^ hash[i];
1279     }
1280
1281     memcpy(text, plain, len);
1282 #if 0
1283     printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1284 #endif
1285
1286     pthread_mutex_unlock(&lock);
1287     return 1;
1288 }
1289
1290 struct realm *id2realm(char *id, uint8_t len) {
1291     struct list_node *entry;
1292     struct realm *realm;
1293     
1294     for (entry = list_first(realms); entry; entry = list_next(entry)) {
1295         realm = (struct realm *)entry->data;
1296         if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1297             debug(DBG_DBG, "found matching realm: %s", realm->name);
1298             return realm;
1299         }
1300     }
1301     return NULL;
1302 }
1303
1304 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
1305     int i;
1306     
1307     pthread_mutex_lock(&to->newrq_mutex);
1308     for (i = 0; i < MAX_REQUESTS; i++)
1309         if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
1310             break;
1311     pthread_mutex_unlock(&to->newrq_mutex);
1312     
1313     return i < MAX_REQUESTS;
1314 }
1315
1316 int attrvalidate(unsigned char *attrs, int length) {
1317     while (length > 1) {
1318         if (ATTRLEN(attrs) < 2) {
1319             debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1320             return 0;
1321         }
1322         length -= ATTRLEN(attrs);
1323         if (length < 0) {
1324             debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1325             return 0;
1326         }
1327         attrs += ATTRLEN(attrs);
1328     }
1329     if (length)
1330         debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1331     return 1;
1332 }
1333
1334 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1335     if (len < 16 || len > 128 || len % 16) {
1336         debug(DBG_WARN, "pwdrecrypt: invalid password length");
1337         return 0;
1338     }
1339         
1340     if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1341         debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1342         return 0;
1343     }
1344 #ifdef DEBUG
1345     printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1346 #endif  
1347     if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1348         debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1349         return 0;
1350     }
1351     return 1;
1352 }
1353
1354 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1355     if (len < 18)
1356         return 0;
1357     if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1358         debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1359         return 0;
1360     }
1361     if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1362         debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1363         return 0;
1364     }
1365     return 1;
1366 }
1367
1368 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1369            char *oldsecret, char *newsecret) {
1370     unsigned char *attr;
1371     
1372     for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1373         debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1374         if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1375             return 0;
1376     }
1377     return 1;
1378 }
1379
1380 void removeattrs(uint8_t *buf, uint8_t *rmattrs) {
1381     uint8_t *attrs, alen;
1382     uint16_t len, rmlen = 0;
1383     
1384     if (!rmattrs)
1385         return;
1386
1387     len = RADLEN(buf) - 20;
1388     attrs = buf + 20;
1389     while (len > 1) {
1390         alen = ATTRLEN(attrs);
1391         len -= alen;
1392         if (strchr((char *)rmattrs, ATTRTYPE(attrs))) {
1393             memmove(attrs, attrs + alen, len);
1394             rmlen += alen;
1395         } else
1396             attrs += alen;
1397     }
1398     if (rmlen)
1399         ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1400 }
1401
1402 /* returns a pointer to the resized attribute value */
1403 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1404     uint8_t *attrs, *attr, vallen;
1405     uint16_t len;
1406     unsigned char *new;
1407     
1408     len = RADLEN(*buf) - 20;
1409     attrs = *buf + 20;
1410
1411     attr = attrget(attrs, len, type);
1412     if (!attr)
1413         return NULL;
1414     
1415     vallen = ATTRVALLEN(attr);
1416     if (vallen == newvallen)
1417         return attr + 2;
1418
1419     len += newvallen - vallen;
1420     if (newvallen > vallen) {
1421         new = realloc(*buf, len + 20);
1422         if (!new) {
1423             debug(DBG_ERR, "resizeattr: malloc failed");
1424             return NULL;
1425         }
1426         if (new != *buf) {
1427             attr += new - *buf;
1428             attrs = new + 20;
1429             *buf = new;
1430         }
1431     }
1432     memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1433     attr[1] = newvallen + 2;
1434     ((uint16_t *)*buf)[1] = htons(len + 20);
1435     return attr + 2;
1436 }
1437                 
1438 int rewriteusername(struct request *rq, char *in) {
1439     size_t nmatch = 10, reslen = 0, start = 0;
1440     regmatch_t pmatch[10], *pfield;
1441     int i;
1442     unsigned char *result;
1443     char *out = rq->from->conf->rewriteattrreplacement;
1444     
1445     if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1446         debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1447         return 1;
1448     }
1449     
1450     rq->origusername = stringcopy(in, 0);
1451     if (!rq->origusername)
1452         return 0;
1453     
1454     for (i = start; out[i]; i++) {
1455         if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1456             pfield = &pmatch[out[i + 1] - '0'];
1457             if (pfield->rm_so >= 0) {
1458                 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1459                 start = i + 2;
1460             }
1461             i++;
1462         }
1463     }
1464     reslen += i - start;
1465
1466     result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1467     if (!result)
1468         return 0;
1469     
1470     start = 0;
1471     reslen = 0;
1472     for (i = start; out[i]; i++) {
1473         if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1474             pfield = &pmatch[out[i + 1] - '0'];
1475             if (pfield->rm_so >= 0) {
1476                 memcpy(result + reslen, out + start, i - start);
1477                 reslen += i - start;
1478                 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1479                 reslen += pfield->rm_eo - pfield->rm_so;
1480                 start = i + 2;
1481             }
1482             i++;
1483         }
1484     }
1485
1486     memcpy(result + reslen, out + start, i - start);
1487     reslen += i - start;
1488     memcpy(in, result, reslen);
1489     in[reslen] = '\0';
1490     return 1;
1491 }
1492
1493 void acclog(unsigned char *attrs, int length, char *host) {
1494     unsigned char *attr;
1495     char username[256];
1496     
1497     attr = attrget(attrs, length, RAD_Attr_User_Name);
1498     if (!attr) {
1499         debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1500         return;
1501     }
1502     memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1503     username[ATTRVALLEN(attr)] = '\0';
1504     debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1505 }
1506         
1507 void respondaccounting(struct request *rq) {
1508     unsigned char *resp;
1509
1510     resp = malloc(20);
1511     if (!resp) {
1512         debug(DBG_ERR, "respondstatusserver: malloc failed");
1513         return;
1514     }
1515     memcpy(resp, rq->buf, 20);
1516     resp[0] = RAD_Accounting_Response;
1517     resp[2] = 0;
1518     resp[3] = 20;
1519     debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1520     sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1521 }
1522
1523 void respondstatusserver(struct request *rq) {
1524     unsigned char *resp;
1525
1526     resp = malloc(20);
1527     if (!resp) {
1528         debug(DBG_ERR, "respondstatusserver: malloc failed");
1529         return;
1530     }
1531     memcpy(resp, rq->buf, 20);
1532     resp[0] = RAD_Access_Accept;
1533     resp[2] = 0;
1534     resp[3] = 20;
1535     debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1536     sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1537 }
1538
1539 void respondreject(struct request *rq, char *message) {
1540     unsigned char *resp;
1541     int len = 20;
1542
1543     if (message && *message)
1544         len += 2 + strlen(message);
1545     
1546     resp = malloc(len);
1547     if (!resp) {
1548         debug(DBG_ERR, "respondreject: malloc failed");
1549         return;
1550     }
1551     memcpy(resp, rq->buf, 20);
1552     resp[0] = RAD_Access_Reject;
1553     *(uint16_t *)(resp + 2) = htons(len);
1554     if (message && *message) {
1555         resp[20] = RAD_Attr_Reply_Message;
1556         resp[21] = len - 20;
1557         memcpy(resp + 22, message, len - 22);
1558     }
1559     sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1560 }
1561
1562 struct server *realm2server(struct realm *realm) {
1563     struct list_node *entry;
1564     struct server *server, *best = NULL;
1565     
1566     for (entry = list_first(realm->srvconfs); entry; entry = list_next(entry)) {
1567         server = ((struct clsrvconf *)entry->data)->servers;
1568         if (!server->connectionok)
1569             continue;
1570         if (!server->loststatsrv)
1571             return server;
1572         if (!best) {
1573             best = server;
1574             continue;
1575         }
1576         if (server->loststatsrv < best->loststatsrv)
1577             best = server;
1578     }
1579     return best;
1580 }
1581
1582 void radsrv(struct request *rq) {
1583     uint8_t code, id, *auth, *attrs, *attr;
1584     uint16_t len;
1585     struct server *to = NULL;
1586     char username[256];
1587     unsigned char newauth[16];
1588     struct realm *realm = NULL;
1589     
1590     code = *(uint8_t *)rq->buf;
1591     id = *(uint8_t *)(rq->buf + 1);
1592     len = RADLEN(rq->buf);
1593     auth = (uint8_t *)(rq->buf + 4);
1594
1595     debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1596     
1597     if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1598         debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1599         freerqdata(rq);
1600         return;
1601     }
1602
1603     len -= 20;
1604     attrs = rq->buf + 20;
1605
1606     if (!attrvalidate(attrs, len)) {
1607         debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1608         freerqdata(rq);
1609         return;
1610     }
1611
1612     attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1613     if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
1614         debug(DBG_WARN, "radsrv: message authentication failed");
1615         freerqdata(rq);
1616         return;
1617     }
1618
1619     if (code != RAD_Access_Request) {
1620         switch (code) {
1621         case RAD_Accounting_Request:
1622             /* when forwarding accounting, also filter attributes, call removeattrs(rq) */
1623             acclog(attrs, len, rq->from->conf->host);
1624             respondaccounting(rq);
1625             break;
1626         case RAD_Status_Server:
1627             respondstatusserver(rq);
1628             break;
1629         }
1630         freerqdata(rq);
1631         return;
1632     }
1633
1634     /* code == RAD_Access_Request */
1635     if (rq->from->conf->removeattrs) {
1636         removeattrs(rq->buf, rq->from->conf->removeattrs);
1637         len = RADLEN(rq->buf) - 20;
1638     }
1639     
1640     attr = attrget(attrs, len, RAD_Attr_User_Name);
1641     if (!attr) {
1642         debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1643         freerqdata(rq);
1644         return;
1645     }
1646     memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1647     username[ATTRVALLEN(attr)] = '\0';
1648
1649     if (rq->from->conf->rewriteattrregex) {
1650         if (!rewriteusername(rq, username)) {
1651             debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1652             freerqdata(rq);
1653             return;
1654         }
1655         len = RADLEN(rq->buf) - 20;
1656         auth = (uint8_t *)(rq->buf + 4);
1657         attrs = rq->buf + 20;
1658     }
1659
1660     if (rq->origusername)
1661         debug(DBG_DBG, "Access Request with username: %s (originally %s)", username, rq->origusername);
1662     else
1663         debug(DBG_DBG, "Access Request with username: %s", username);
1664         
1665     realm = id2realm(username, strlen(username));
1666     if (!realm) {
1667         debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1668         freerqdata(rq);
1669         return;
1670     }
1671         
1672     to = realm2server(realm);
1673     if (to && rqinqueue(to, rq->from, id)) {
1674         debug(DBG_INFO, "radsrv: already got request from host %s with id %d, ignoring", rq->from->conf->host, id);
1675         freerqdata(rq);
1676         return;
1677     }
1678
1679     if (!to) {
1680         if (realm->message) {
1681             debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, username);
1682             respondreject(rq, realm->message);
1683         }
1684         freerqdata(rq);
1685         return;
1686     }
1687     
1688     if (!RAND_bytes(newauth, 16)) {
1689         debug(DBG_WARN, "radsrv: failed to generate random auth");
1690         freerqdata(rq);
1691         return;
1692     }
1693
1694 #ifdef DEBUG
1695     printfchars(NULL, "auth", "%02x ", auth, 16);
1696 #endif
1697
1698     attr = attrget(attrs, len, RAD_Attr_User_Password);
1699     if (attr) {
1700         debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1701         if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1702             freerqdata(rq);
1703             return;
1704         }
1705     }
1706     
1707     attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1708     if (attr) {
1709         debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1710         if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1711             freerqdata(rq);
1712             return;
1713         }
1714     }
1715
1716     rq->origid = id;
1717     memcpy(rq->origauth, auth, 16);
1718     memcpy(auth, newauth, 16);
1719     sendrq(to, rq);
1720 }
1721
1722 int replyh(struct server *server, unsigned char *buf) {
1723     struct client *from;
1724     struct request *rq;
1725     int i, len, sublen;
1726     unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
1727     struct sockaddr_storage fromsa;
1728     char tmp[256];
1729     
1730     server->connectionok = 1;
1731     server->loststatsrv = 0;
1732         
1733     i = buf[1]; /* i is the id */
1734
1735     switch (*buf) {
1736     case RAD_Access_Accept:
1737         debug(DBG_DBG, "got Access Accept with id %d", i);
1738         break;
1739     case RAD_Access_Reject:
1740         debug(DBG_DBG, "got Access Reject with id %d", i);
1741         break;
1742     case RAD_Access_Challenge:
1743         debug(DBG_DBG, "got Access Challenge with id %d", i);
1744         break;
1745     default:
1746         debug(DBG_INFO, "replyh: discarding, only accept access accept, access reject and access challenge messages");
1747         return 0;
1748     }
1749
1750     rq = server->requests + i;
1751         
1752     pthread_mutex_lock(&server->newrq_mutex);
1753     if (!rq->buf || !rq->tries) {
1754         pthread_mutex_unlock(&server->newrq_mutex);
1755         debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
1756         return 0;
1757     }
1758
1759     if (rq->received) {
1760         pthread_mutex_unlock(&server->newrq_mutex);
1761         debug(DBG_INFO, "replyh: already received, ignoring reply");
1762         return 0;
1763     }
1764         
1765     if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
1766         pthread_mutex_unlock(&server->newrq_mutex);
1767         debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
1768         return 0;
1769     }
1770         
1771     from = rq->from;
1772     len = RADLEN(buf) - 20;
1773     attrs = buf + 20;
1774
1775     if (!attrvalidate(attrs, len)) {
1776         pthread_mutex_unlock(&server->newrq_mutex);
1777         debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
1778         return 0;
1779     }
1780         
1781     /* Message Authenticator */
1782     messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1783     if (messageauth) {
1784         if (ATTRVALLEN(messageauth) != 16) {
1785             pthread_mutex_unlock(&server->newrq_mutex);
1786             debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
1787             return 0;
1788         }
1789         memcpy(tmp, buf + 4, 16);
1790         memcpy(buf + 4, rq->buf + 4, 16);
1791         if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
1792             pthread_mutex_unlock(&server->newrq_mutex);
1793             debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
1794             return 0;
1795         }
1796         memcpy(buf + 4, tmp, 16);
1797         debug(DBG_DBG, "replyh: message auth ok");
1798     }
1799         
1800     if (*rq->buf == RAD_Status_Server) {
1801         rq->received = 1;
1802         pthread_mutex_unlock(&server->newrq_mutex);
1803         debug(DBG_INFO, "replyh: got status server response from %s", server->conf->host);
1804         return 0;
1805     }
1806
1807     if (server->conf->removeattrs) {
1808         removeattrs(buf, server->conf->removeattrs);
1809         len = RADLEN(buf) - 20;
1810     }
1811     
1812     /* MS MPPE */
1813     for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1814         if (ATTRVALLEN(attr) <= 4)
1815             break;
1816             
1817         if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55)  /* 311 == MS */
1818             continue;
1819             
1820         sublen = ATTRVALLEN(attr) - 4;
1821         subattrs = ATTRVAL(attr) + 4;  
1822         if (!attrvalidate(subattrs, sublen) ||
1823             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1824                     rq, server->conf->secret, from->conf->secret) ||
1825             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1826                     rq, server->conf->secret, from->conf->secret))
1827             break;
1828     }
1829     if (attr) {
1830         pthread_mutex_unlock(&server->newrq_mutex);
1831         debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1832         return 0;
1833     }
1834         
1835     if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject) {
1836         attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
1837         /* we know the attribute exists */
1838         memcpy(tmp, ATTRVAL(attr), ATTRVALLEN(attr));
1839         tmp[ATTRVALLEN(attr)] = '\0';
1840         switch (*buf) {
1841         case RAD_Access_Accept:
1842             if (rq->origusername)
1843                 debug(DBG_INFO, "Access Accept for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1844             else
1845                 debug(DBG_INFO, "Access Accept for %s from %s", tmp, server->conf->host);
1846             break;
1847         case RAD_Access_Reject:
1848             if (rq->origusername)
1849                 debug(DBG_INFO, "Access Reject for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1850             else
1851                 debug(DBG_INFO, "Access Reject for %s from %s", tmp, server->conf->host);
1852             break;
1853         }
1854     }
1855         
1856     buf[1] = (char)rq->origid;
1857     memcpy(buf + 4, rq->origauth, 16);
1858 #ifdef DEBUG    
1859     printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1860 #endif
1861
1862     if (rq->origusername) {
1863         username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
1864         if (!username) {
1865             pthread_mutex_unlock(&server->newrq_mutex);
1866             debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1867             return 0;
1868         }
1869         memcpy(username, rq->origusername, strlen(rq->origusername));
1870         len = RADLEN(buf) - 20;
1871         attrs = buf + 20;
1872         if (messageauth)
1873             messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1874     }
1875         
1876     if (messageauth) {
1877         if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
1878             pthread_mutex_unlock(&server->newrq_mutex);
1879             debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
1880             return 0;
1881         }
1882         debug(DBG_DBG, "replyh: computed messageauthattr");
1883     }
1884
1885     if (from->conf->type == 'U')
1886         fromsa = rq->fromsa;
1887     /* once we set received = 1, rq may be reused */
1888     rq->received = 1;
1889     pthread_mutex_unlock(&server->newrq_mutex);
1890
1891     debug(DBG_DBG, "replyh: giving packet back to where it came from");
1892     sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
1893     return 1;
1894 }
1895
1896 void *udpclientrd(void *arg) {
1897     struct server *server;
1898     unsigned char *buf;
1899     int *s = (int *)arg;
1900     
1901     for (;;) {
1902         server = NULL;
1903         buf = radudpget(*s, NULL, &server, NULL);
1904         if (!replyh(server, buf))
1905             free(buf);
1906     }
1907 }
1908
1909 void *tlsclientrd(void *arg) {
1910     struct server *server = (struct server *)arg;
1911     unsigned char *buf;
1912     struct timeval lastconnecttry;
1913     
1914     for (;;) {
1915         /* yes, lastconnecttry is really necessary */
1916         lastconnecttry = server->lastconnecttry;
1917         buf = radtlsget(server->ssl);
1918         if (!buf) {
1919             tlsconnect(server, &lastconnecttry, "clientrd");
1920             continue;
1921         }
1922
1923         if (!replyh(server, buf))
1924             free(buf);
1925     }
1926 }
1927
1928 void *clientwr(void *arg) {
1929     struct server *server = (struct server *)arg;
1930     struct request *rq;
1931     pthread_t tlsclientrdth;
1932     int i;
1933     uint8_t rnd;
1934     struct timeval now, lastsend;
1935     struct timespec timeout;
1936     struct request statsrvrq;
1937     unsigned char statsrvbuf[38];
1938
1939     memset(&timeout, 0, sizeof(struct timespec));
1940     
1941     if (server->conf->statusserver) {
1942         memset(&statsrvrq, 0, sizeof(struct request));
1943         memset(statsrvbuf, 0, sizeof(statsrvbuf));
1944         statsrvbuf[0] = RAD_Status_Server;
1945         statsrvbuf[3] = 38;
1946         statsrvbuf[20] = RAD_Attr_Message_Authenticator;
1947         statsrvbuf[21] = 18;
1948         gettimeofday(&lastsend, NULL);
1949     }
1950     
1951     if (server->conf->type == 'U') {
1952         server->connectionok = 1;
1953     } else {
1954         tlsconnect(server, NULL, "new client");
1955         server->connectionok = 1;
1956         if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server))
1957             debugx(1, DBG_ERR, "clientwr: pthread_create failed");
1958     }
1959     
1960     for (;;) {
1961         pthread_mutex_lock(&server->newrq_mutex);
1962         if (!server->newrq) {
1963             gettimeofday(&now, NULL);
1964             if (server->conf->statusserver) {
1965                 /* random 0-7 seconds */
1966                 RAND_bytes(&rnd, 1);
1967                 rnd /= 32;
1968                 if (!timeout.tv_sec || timeout.tv_sec - now.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
1969                     timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
1970             }   
1971             if (timeout.tv_sec) {
1972                 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1973                 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1974                 timeout.tv_sec = 0;
1975             } else {
1976                 debug(DBG_DBG, "clientwr: waiting for new request");
1977                 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1978             }
1979         }
1980         if (server->newrq) {
1981             debug(DBG_DBG, "clientwr: got new request");
1982             server->newrq = 0;
1983         } else
1984             debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1985         pthread_mutex_unlock(&server->newrq_mutex);
1986
1987         for (i = 0; i < MAX_REQUESTS; i++) {
1988             pthread_mutex_lock(&server->newrq_mutex);
1989             while (i < MAX_REQUESTS && !server->requests[i].buf)
1990                 i++;
1991             if (i == MAX_REQUESTS) {
1992                 pthread_mutex_unlock(&server->newrq_mutex);
1993                 break;
1994             }
1995             rq = server->requests + i;
1996
1997             if (rq->received) {
1998                 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
1999                 if (rq->buf) {
2000                     debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2001                     freerqdata(rq);
2002                     /* setting this to NULL means that it can be reused */
2003                     rq->buf = NULL;
2004                 }
2005                 pthread_mutex_unlock(&server->newrq_mutex);
2006                 continue;
2007             }
2008             
2009             gettimeofday(&now, NULL);
2010             if (now.tv_sec < rq->expiry.tv_sec) {
2011                 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2012                     timeout.tv_sec = rq->expiry.tv_sec;
2013                 pthread_mutex_unlock(&server->newrq_mutex);
2014                 continue;
2015             }
2016
2017             if (rq->tries == (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
2018                               ? 1 : REQUEST_RETRIES)) {
2019                 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2020                 if (*rq->buf == RAD_Status_Server) {
2021                     debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->conf->host);
2022                     if (server->loststatsrv < 255)
2023                         server->loststatsrv++;
2024                 }
2025                 freerqdata(rq);
2026                 /* setting this to NULL means that it can be reused */
2027                 rq->buf = NULL;
2028                 pthread_mutex_unlock(&server->newrq_mutex);
2029                 continue;
2030             }
2031             pthread_mutex_unlock(&server->newrq_mutex);
2032
2033             rq->expiry.tv_sec = now.tv_sec +
2034                 (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
2035                  ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
2036             if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2037                 timeout.tv_sec = rq->expiry.tv_sec;
2038             rq->tries++;
2039             clientradput(server, server->requests[i].buf);
2040             gettimeofday(&lastsend, NULL);
2041         }
2042         if (server->conf->statusserver) {
2043             gettimeofday(&now, NULL);
2044             if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
2045                 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2046                     debug(DBG_WARN, "clientwr: failed to generate random auth");
2047                     continue;
2048                 }
2049                 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2050                 if (!statsrvrq.buf) {
2051                     debug(DBG_ERR, "clientwr: malloc failed");
2052                     continue;
2053                 }
2054                 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2055                 debug(DBG_DBG, "clientwr: sending status server to %s", server->conf->host);
2056                 lastsend.tv_sec = now.tv_sec;
2057                 sendrq(server, &statsrvrq);
2058             }
2059         }
2060     }
2061 }
2062
2063 void *udpserverwr(void *arg) {
2064     struct replyq *replyq = udp_server_replyq;
2065     struct reply *reply;
2066     
2067     for (;;) {
2068         pthread_mutex_lock(&replyq->mutex);
2069         while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2070             debug(DBG_DBG, "udp server writer, waiting for signal");
2071             pthread_cond_wait(&replyq->cond, &replyq->mutex);
2072             debug(DBG_DBG, "udp server writer, got signal");
2073         }
2074         pthread_mutex_unlock(&replyq->mutex);
2075
2076         if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
2077                    (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2078             debug(DBG_WARN, "sendudp: send failed");
2079         free(reply->buf);
2080         free(reply);
2081     }
2082 }
2083
2084 void *udpserverrd(void *arg) {
2085     struct request rq;
2086     pthread_t udpserverwrth;
2087     struct clsrvconf *listenres;
2088
2089     listenres = resolve_hostport('U', options.listenudp, DEFAULT_UDP_PORT);
2090     if ((udp_server_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2091         debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2092
2093     debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
2094           listenres->host ? listenres->host : "*", listenres->port);
2095     free(listenres);
2096     
2097     if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
2098         debugx(1, DBG_ERR, "pthread_create failed");
2099     
2100     for (;;) {
2101         memset(&rq, 0, sizeof(struct request));
2102         rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
2103         radsrv(&rq);
2104     }
2105 }
2106
2107 void *udpaccserverrd(void *arg) {
2108     struct request rq;
2109     struct clsrvconf *listenres;
2110     
2111     listenres = resolve_hostport('U', options.listenaccudp, DEFAULT_UDP_PORT);
2112     if ((udp_accserver_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2113         debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2114
2115     debug(DBG_WARN, "udpaccserverrd: listening for UDP on %s:%s",
2116           listenres->host ? listenres->host : "*", listenres->port);
2117     free(listenres);
2118     
2119     for (;;) {
2120         memset(&rq, 0, sizeof(struct request));
2121         rq.buf = radudpget(udp_accserver_sock, &rq.from, NULL, &rq.fromsa);
2122         if (*(uint8_t *)rq.buf == RAD_Accounting_Request) {
2123             radsrv(&rq);
2124             continue;
2125         }
2126         debug(DBG_INFO, "udpaccserverrd: got something other than accounting-request, ignoring");
2127         freerqdata(&rq);
2128     }
2129 }
2130
2131 void *tlsserverwr(void *arg) {
2132     int cnt;
2133     unsigned long error;
2134     struct client *client = (struct client *)arg;
2135     struct replyq *replyq;
2136     struct reply *reply;
2137     
2138     debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
2139     replyq = client->replyq;
2140     for (;;) {
2141         pthread_mutex_lock(&replyq->mutex);
2142         while (!list_first(replyq->replies)) {
2143             if (client->ssl) {      
2144                 debug(DBG_DBG, "tls server writer, waiting for signal");
2145                 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2146                 debug(DBG_DBG, "tls server writer, got signal");
2147             }
2148             if (!client->ssl) {
2149                 /* ssl might have changed while waiting */
2150                 pthread_mutex_unlock(&replyq->mutex);
2151                 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2152                 pthread_exit(NULL);
2153             }
2154         }
2155         reply = (struct reply *)list_shift(replyq->replies);
2156         pthread_mutex_unlock(&replyq->mutex);
2157         cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2158         if (cnt > 0)
2159             debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
2160                   cnt, RADLEN(reply->buf));
2161         else
2162             while ((error = ERR_get_error()))
2163                 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2164         free(reply->buf);
2165         free(reply);
2166     }
2167 }
2168
2169 void *tlsserverrd(void *arg) {
2170     struct request rq;
2171     unsigned long error;
2172     int s;
2173     struct client *client = (struct client *)arg;
2174     pthread_t tlsserverwrth;
2175     SSL *ssl;
2176     
2177     debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2178     ssl = client->ssl;
2179
2180     if (SSL_accept(ssl) <= 0) {
2181         while ((error = ERR_get_error()))
2182             debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2183         debug(DBG_ERR, "SSL_accept failed");
2184         goto errexit;
2185     }
2186     if (tlsverifycert(client->ssl, client->conf)) {
2187         if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2188             debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2189             goto errexit;
2190         }
2191         for (;;) {
2192             memset(&rq, 0, sizeof(struct request));
2193             rq.buf = radtlsget(client->ssl);
2194             if (!rq.buf)
2195                 break;
2196             debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2197             rq.from = client;
2198             radsrv(&rq);
2199         }
2200         debug(DBG_ERR, "tlsserverrd: connection lost");
2201         /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2202         client->ssl = NULL;
2203         pthread_mutex_lock(&client->replyq->mutex);
2204         pthread_cond_signal(&client->replyq->cond);
2205         pthread_mutex_unlock(&client->replyq->mutex);
2206         debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2207         pthread_join(tlsserverwrth, NULL);
2208     }
2209     
2210  errexit:
2211     s = SSL_get_fd(ssl);
2212     SSL_free(ssl);
2213     shutdown(s, SHUT_RDWR);
2214     close(s);
2215     debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->conf->host);
2216     removeclient(client);
2217     pthread_exit(NULL);
2218 }
2219
2220 int tlslistener() {
2221     pthread_t tlsserverth;
2222     int s, snew;
2223     struct sockaddr_storage from;
2224     size_t fromlen = sizeof(from);
2225     struct clsrvconf *conf;
2226     struct client *client;
2227     struct clsrvconf *listenres;
2228     
2229     listenres = resolve_hostport('T', options.listentcp, DEFAULT_TLS_PORT);
2230     if ((s = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2231         debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
2232     
2233     listen(s, 0);
2234     debug(DBG_WARN, "listening for incoming TCP on %s:%s", listenres->host ? listenres->host : "*", listenres->port);
2235     free(listenres);
2236     
2237     for (;;) {
2238         snew = accept(s, (struct sockaddr *)&from, &fromlen);
2239         if (snew < 0) {
2240             debug(DBG_WARN, "accept failed");
2241             continue;
2242         }
2243         debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2244
2245         conf = find_conf('T', (struct sockaddr *)&from, clconfs, NULL);
2246         if (!conf) {
2247             debug(DBG_WARN, "ignoring request, not a known TLS client");
2248             shutdown(snew, SHUT_RDWR);
2249             close(snew);
2250             continue;
2251         }
2252
2253         client = addclient(conf);
2254
2255         if (!client) {
2256             debug(DBG_WARN, "Failed to create new client instance");
2257             shutdown(snew, SHUT_RDWR);
2258             close(snew);
2259             continue;
2260         }
2261         client->ssl = SSL_new(client->conf->ssl_ctx);
2262         SSL_set_fd(client->ssl, snew);
2263         if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
2264             debug(DBG_ERR, "tlslistener: pthread_create failed");
2265             SSL_free(client->ssl);
2266             removeclient(client);
2267             shutdown(snew, SHUT_RDWR);
2268             close(snew);
2269             continue;
2270         }
2271         pthread_detach(tlsserverth);
2272     }
2273     return 0;
2274 }
2275
2276 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
2277     struct tls *new;
2278     SSL_CTX *ctx;
2279     STACK_OF(X509_NAME) *calist;
2280     int i;
2281     unsigned long error;
2282     
2283     if (!certfile || !certkeyfile)
2284         debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2285
2286     if (!cacertfile && !cacertpath)
2287         debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2288
2289     if (!ssl_locks) {
2290         ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2291         ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2292         for (i = 0; i < CRYPTO_num_locks(); i++) {
2293             ssl_lock_count[i] = 0;
2294             pthread_mutex_init(&ssl_locks[i], NULL);
2295         }
2296         CRYPTO_set_id_callback(ssl_thread_id);
2297         CRYPTO_set_locking_callback(ssl_locking_callback);
2298
2299         SSL_load_error_strings();
2300         SSL_library_init();
2301
2302         while (!RAND_status()) {
2303             time_t t = time(NULL);
2304             pid_t pid = getpid();
2305             RAND_seed((unsigned char *)&t, sizeof(time_t));
2306             RAND_seed((unsigned char *)&pid, sizeof(pid));
2307         }
2308     }
2309     ctx = SSL_CTX_new(TLSv1_method());
2310     if (certkeypwd) {
2311         SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2312         SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2313     }
2314     if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2315         !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2316         !SSL_CTX_check_private_key(ctx) ||
2317         !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2318         while ((error = ERR_get_error()))
2319             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2320         debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2321     }
2322
2323     calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
2324     if (!cacertfile || calist) {
2325         if (cacertpath) {
2326             if (!calist)
2327                 calist = sk_X509_NAME_new_null();
2328             if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
2329                 sk_X509_NAME_free(calist);
2330                 calist = NULL;
2331             }
2332         }
2333     }
2334     if (!calist) {
2335         while ((error = ERR_get_error()))
2336             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2337         debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
2338     }
2339     SSL_CTX_set_client_CA_list(ctx, calist);
2340     
2341     SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2342     SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2343
2344     new = malloc(sizeof(struct tls));
2345     if (!new || !list_push(tlsconfs, new))
2346         debugx(1, DBG_ERR, "malloc failed");
2347
2348     memset(new, 0, sizeof(struct tls));
2349     new->name = stringcopy(value, 0);
2350     if (!new->name)
2351         debugx(1, DBG_ERR, "malloc failed");
2352     new->ctx = ctx;
2353     new->count = 0;
2354     debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2355 }
2356
2357 void tlsfree() {
2358     struct list_node *entry;
2359     struct tls *t;
2360     
2361     for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2362         t = (struct tls *)entry->data;
2363         if (t->name)
2364             free(t->name);
2365         if (!t->count)
2366             SSL_CTX_free(t->ctx);
2367     }
2368     list_destroy(tlsconfs);
2369     tlsconfs = NULL;
2370 }
2371
2372 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2373     struct list_node *entry;
2374     struct tls *t, *t1 = NULL, *t2 = NULL;
2375     
2376     for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2377         t = (struct tls *)entry->data;
2378         if (!strcasecmp(t->name, alt1)) {
2379             t1 = t;
2380             break;
2381         }
2382         if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2383             t2 = t;
2384     }
2385
2386     t = (t1 ? t1 : t2);
2387     if (!t)
2388         return NULL;
2389     t->count++;
2390     return t->ctx;
2391 }
2392
2393 void addrealm(char *value, char **servers, char *message) {
2394     int n;
2395     struct realm *realm;
2396     char *s, *regex = NULL;
2397     struct list_node *entry;
2398     struct clsrvconf *conf;
2399     
2400     if (*value == '/') {
2401         /* regexp, remove optional trailing / if present */
2402         if (value[strlen(value) - 1] == '/')
2403             value[strlen(value) - 1] = '\0';
2404     } else {
2405         /* not a regexp, let us make it one */
2406         if (*value == '*' && !value[1])
2407             regex = stringcopy(".*", 0);
2408         else {
2409             for (n = 0, s = value; *s;)
2410                 if (*s++ == '.')
2411                     n++;
2412             regex = malloc(strlen(value) + n + 3);
2413             if (regex) {
2414                 regex[0] = '@';
2415                 for (n = 1, s = value; *s; s++) {
2416                     if (*s == '.')
2417                         regex[n++] = '\\';
2418                     regex[n++] = *s;
2419                 }
2420                 regex[n++] = '$';
2421                 regex[n] = '\0';
2422             }
2423         }
2424         if (!regex)
2425             debugx(1, DBG_ERR, "malloc failed");
2426         debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2427     }
2428
2429     realm = malloc(sizeof(struct realm));
2430     if (!realm)
2431         debugx(1, DBG_ERR, "malloc failed");
2432     
2433     memset(realm, 0, sizeof(struct realm));
2434     realm->name = stringcopy(value, 0);
2435     if (!realm->name)
2436         debugx(1, DBG_ERR, "malloc failed");
2437     if (message && strlen(message) > 253)
2438         debugx(1, DBG_ERR, "ReplyMessage can be at most 253 bytes");
2439     realm->message = message;
2440     
2441     if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB))
2442         debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2443     if (regex)
2444         free(regex);
2445     
2446     if (servers && *servers) {
2447         realm->srvconfs = list_create();
2448         if (!realm->srvconfs)
2449             debugx(1, DBG_ERR, "malloc failed");
2450         for (n = 0; servers[n]; n++) {
2451             for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2452                 conf = (struct clsrvconf *)entry->data;
2453                 if (!strcasecmp(servers[n], conf->name))
2454                     break;
2455             }
2456             if (!entry)
2457                 debugx(1, DBG_ERR, "addrealm failed, no server %s", servers[n]);
2458             if (!list_push(realm->srvconfs, conf))
2459                 debugx(1, DBG_ERR, "malloc failed");
2460             debug(DBG_DBG, "addrealm: added server %s for realm %s", conf->name, value);
2461         }
2462     } else
2463         realm->srvconfs = NULL;
2464     
2465     if (!list_push(realms, realm))
2466         debugx(1, DBG_ERR, "malloc failed");
2467     debug(DBG_DBG, "addrealm: added realm %s", value);
2468 }
2469
2470 struct gconffile *openconfigfile(const char *filename) {
2471     FILE *f;
2472     char pathname[100], *base = NULL;
2473     struct gconffile *cf = NULL;
2474     
2475     f = pushgconffile(&cf, filename);
2476     if (f) {
2477         debug(DBG_DBG, "reading config file %s", filename);
2478         return cf;
2479     }
2480
2481     if (strlen(filename) + 1 <= sizeof(pathname)) {
2482         /* basename() might modify the string */
2483         strcpy(pathname, filename);
2484         base = basename(pathname);
2485         f = pushgconffile(&cf, base);
2486     }
2487
2488     if (!f)
2489         debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
2490     
2491     debug(DBG_DBG, "reading config file %s", base);
2492     return cf;
2493 }
2494
2495 int addmatchcertattr(struct clsrvconf *conf, char *matchcertattr) {
2496     char *v;
2497     
2498     v = matchcertattr + 20;
2499     if (strncasecmp(matchcertattr, "SubjectAltName:URI:/", 20) || !*v)
2500         return 0;
2501     /* regexp, remove optional trailing / if present */
2502     if (v[strlen(v) - 1] == '/')
2503         v[strlen(v) - 1] = '\0';
2504     if (!*v)
2505         return 0;
2506
2507     conf->certuriregex = malloc(sizeof(regex_t));
2508     if (!conf->certuriregex) {
2509         debug(DBG_ERR, "malloc failed");
2510         return 0;
2511     }
2512     if (regcomp(conf->certuriregex, v, REG_ICASE | REG_NOSUB)) {
2513         free(conf->certuriregex);
2514         conf->certuriregex = NULL;
2515         debug(DBG_ERR, "failed to compile regular expression %s", v);
2516         return 0;
2517     }
2518     return 1;
2519 }
2520
2521 int addrewriteattr(struct clsrvconf *conf, char *rewriteattr) {
2522     char *v, *w;
2523     
2524     v = rewriteattr + 11;
2525     if (strncasecmp(rewriteattr, "User-Name:/", 11) || !*v)
2526         return 0;
2527     /* regexp, remove optional trailing / if present */
2528     if (v[strlen(v) - 1] == '/')
2529         v[strlen(v) - 1] = '\0';
2530
2531     w = strchr(v, '/');
2532     if (!*w)
2533         return 0;
2534     *w = '\0';
2535     w++;
2536     
2537     conf->rewriteattrregex = malloc(sizeof(regex_t));
2538     if (!conf->rewriteattrregex) {
2539         debug(DBG_ERR, "malloc failed");
2540         return 0;
2541     }
2542
2543     conf->rewriteattrreplacement = stringcopy(w, 0);
2544     if (!conf->rewriteattrreplacement) {
2545         free(conf->rewriteattrregex);
2546         conf->rewriteattrregex = NULL;
2547         return 0;
2548     }
2549     
2550     if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
2551         free(conf->rewriteattrregex);
2552         conf->rewriteattrregex = NULL;
2553         free(conf->rewriteattrreplacement);
2554         conf->rewriteattrreplacement = NULL;
2555         debug(DBG_ERR, "failed to compile regular expression %s", v);
2556         return 0;
2557     }
2558
2559     return 1;
2560 }
2561
2562 /* should accept both names and numeric values, only numeric right now */
2563 uint8_t attrname2val(char *attrname) {
2564     int val = 0;
2565     
2566     val = atoi(attrname);
2567     return val > 0 && val < 256 ? val : 0;
2568 }
2569
2570 void rewritefree() {
2571     struct list_node *entry;
2572     struct rewrite *r;
2573     
2574     for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
2575         r = (struct rewrite *)entry->data;
2576         if (r->name)
2577             free(r->name);
2578         if (!r->count)
2579             free(r->removeattrs);
2580     }
2581     list_destroy(rewriteconfs);
2582     rewriteconfs = NULL;
2583 }
2584
2585 uint8_t *getrewrite(char *alt1, char *alt2) {
2586     struct list_node *entry;
2587     struct rewrite *r, *r1 = NULL, *r2 = NULL;
2588     
2589     for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
2590         r = (struct rewrite *)entry->data;
2591         if (!strcasecmp(r->name, alt1)) {
2592             r1 = r;
2593             break;
2594         }
2595         if (!r2 && alt2 && !strcasecmp(r->name, alt2))
2596             r2 = r;
2597     }
2598
2599     r = (r1 ? r1 : r2);
2600     if (!r)
2601         return NULL;
2602     r->count++;
2603     return r->removeattrs;
2604 }
2605
2606 void addrewrite(char *value, char **attrs) {
2607     struct rewrite *new;
2608     int i, n;
2609     uint8_t *a;
2610
2611     n = 0;
2612     if (attrs)
2613         for (; attrs[n]; n++);
2614     a = malloc((n + 1) * sizeof(uint8_t));
2615     if (!a)
2616         debugx(1, DBG_ERR, "malloc failed");
2617     
2618     for (i = 0; i < n; i++)
2619         if (!(a[i] = attrname2val(attrs[i])))
2620             debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
2621     a[i] = 0;
2622     
2623     new = malloc(sizeof(struct rewrite));
2624     if (!new || !list_push(rewriteconfs, new))
2625         debugx(1, DBG_ERR, "malloc failed");
2626
2627     memset(new, 0, sizeof(struct rewrite));
2628     new->name = stringcopy(value, 0);
2629     if (!new->name)
2630         debugx(1, DBG_ERR, "malloc failed");
2631     new->removeattrs = a;
2632     debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2633 }
2634
2635 void confclient_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2636     char *type = NULL, *tls = NULL, *matchcertattr = NULL, *rewrite = NULL, *rewriteattr = NULL;
2637     struct clsrvconf *conf;
2638     
2639     debug(DBG_DBG, "confclient_cb called for %s", block);
2640
2641     conf = malloc(sizeof(struct clsrvconf));
2642     if (!conf || !list_push(clconfs, conf))
2643         debugx(1, DBG_ERR, "malloc failed");
2644     memset(conf, 0, sizeof(struct clsrvconf));
2645     
2646     getgenericconfig(cf, block,
2647                      "type", CONF_STR, &type,
2648                      "host", CONF_STR, &conf->host,
2649                      "secret", CONF_STR, &conf->secret,
2650                      "tls", CONF_STR, &tls,
2651                      "matchcertificateattribute", CONF_STR, &matchcertattr,
2652                      "rewrite", CONF_STR, &rewrite,
2653                      "rewriteattribute", CONF_STR, &rewriteattr,
2654                      NULL
2655                      );
2656
2657     /* leave conf->name to be NULL for clients */
2658     if (!conf->host)
2659         conf->host = stringcopy(val, 0);
2660     
2661     if (type && !strcasecmp(type, "udp")) {
2662         conf->type = 'U';
2663         client_udp_count++;
2664     } else if (type && !strcasecmp(type, "tls")) {
2665         conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultclient", "default");
2666         if (!conf->ssl_ctx)
2667             debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2668         if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2669             debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2670         conf->type = 'T';
2671         client_tls_count++;
2672     } else
2673         debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2674     free(type);
2675     if (tls)
2676         free(tls);
2677     if (matchcertattr)
2678         free(matchcertattr);
2679     
2680     conf->removeattrs = rewrite ? getrewrite(rewrite, NULL) : getrewrite("defaultclient", "default");
2681     
2682     if (rewriteattr) {
2683         if (!addrewriteattr(conf, rewriteattr))
2684             debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2685         free(rewriteattr);
2686     }
2687     
2688     if (!resolvepeer(conf, 0))
2689         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2690     
2691     if (!conf->secret) {
2692         if (conf->type == 'U')
2693             debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2694         conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2695     }
2696 }
2697
2698 void confserver_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2699     char *type = NULL, *tls = NULL, *matchcertattr = NULL, *statusserver = NULL, *rewrite = NULL;
2700     struct clsrvconf *conf;
2701     
2702     debug(DBG_DBG, "confserver_cb called for %s", block);
2703
2704     conf = malloc(sizeof(struct clsrvconf));
2705     if (!conf || !list_push(srvconfs, conf))
2706         debugx(1, DBG_ERR, "malloc failed");
2707     memset(conf, 0, sizeof(struct clsrvconf));
2708     
2709     getgenericconfig(cf, block,
2710                      "type", CONF_STR, &type,
2711                      "host", CONF_STR, &conf->host,
2712                      "port", CONF_STR, &conf->port,
2713                      "secret", CONF_STR, &conf->secret,
2714                      "tls", CONF_STR, &tls,
2715                      "matchcertificateattribute", CONF_STR, &matchcertattr,
2716                      "rewrite", CONF_STR, &rewrite,
2717                      "StatusServer", CONF_STR, &statusserver,
2718                      NULL
2719                      );
2720
2721     conf->name = stringcopy(val, 0);
2722     if (!conf->host)
2723         conf->host = stringcopy(val, 0);
2724     
2725     if (type && !strcasecmp(type, "udp")) {
2726         conf->type = 'U';
2727         server_udp_count++;
2728         if (!conf->port)
2729             conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
2730     } else if (type && !strcasecmp(type, "tls")) {
2731         conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultserver", "default");
2732         if (!conf->ssl_ctx)
2733             debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2734         if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2735             debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2736         if (!conf->port)
2737             conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
2738         conf->type = 'T';
2739         server_tls_count++;
2740     } else
2741         debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2742     free(type);
2743     if (tls)
2744         free(tls);
2745     if (matchcertattr)
2746         free(matchcertattr);
2747     
2748     conf->removeattrs = rewrite ? getrewrite(rewrite, NULL) : getrewrite("defaultserver", "default");
2749     
2750     if (!resolvepeer(conf, 0))
2751         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2752     
2753     if (!conf->secret) {
2754         if (conf->type == 'U')
2755             debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2756         conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2757     }
2758     
2759     if (statusserver) {
2760         if (!strcasecmp(statusserver, "on"))
2761             conf->statusserver = 1;
2762         else if (strcasecmp(statusserver, "off"))
2763             debugx(1, DBG_ERR, "error in block %s, StatusServer is %s, must be on or off", block, statusserver);
2764         free(statusserver);
2765     }
2766 }
2767
2768 void confrealm_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2769     char **servers = NULL, *msg = NULL;
2770     
2771     debug(DBG_DBG, "confrealm_cb called for %s", block);
2772     
2773     getgenericconfig(cf, block,
2774                      "server", CONF_MSTR, &servers,
2775                      "ReplyMessage", CONF_STR, &msg,
2776                      NULL
2777                      );
2778
2779     addrealm(val, servers, msg);
2780     free(servers);
2781 }
2782
2783 void conftls_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2784     char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
2785     
2786     debug(DBG_DBG, "conftls_cb called for %s", block);
2787     
2788     getgenericconfig(cf, block,
2789                      "CACertificateFile", CONF_STR, &cacertfile,
2790                      "CACertificatePath", CONF_STR, &cacertpath,
2791                      "CertificateFile", CONF_STR, &certfile,
2792                      "CertificateKeyFile", CONF_STR, &certkeyfile,
2793                      "CertificateKeyPassword", CONF_STR, &certkeypwd,
2794                      NULL
2795                      );
2796     
2797     tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
2798     free(cacertfile);
2799     free(cacertpath);
2800     free(certfile);
2801     free(certkeyfile);
2802     free(certkeypwd);
2803 }
2804
2805 void confrewrite_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2806     char **attrs = NULL;
2807     
2808     debug(DBG_DBG, "confrewrite_cb called for %s", block);
2809     
2810     getgenericconfig(cf, block,
2811                      "removeAttribute", CONF_MSTR, &attrs,
2812                      NULL
2813                      );
2814     addrewrite(val, attrs);
2815     free(attrs);
2816 }
2817
2818 void getmainconfig(const char *configfile) {
2819     char *loglevel = NULL;
2820     struct gconffile *cfs;
2821
2822     cfs = openconfigfile(configfile);
2823     memset(&options, 0, sizeof(options));
2824     
2825     clconfs = list_create();
2826     if (!clconfs)
2827         debugx(1, DBG_ERR, "malloc failed");
2828     
2829     srvconfs = list_create();
2830     if (!srvconfs)
2831         debugx(1, DBG_ERR, "malloc failed");
2832     
2833     realms = list_create();
2834     if (!realms)
2835         debugx(1, DBG_ERR, "malloc failed");    
2836  
2837     tlsconfs = list_create();
2838     if (!tlsconfs)
2839         debugx(1, DBG_ERR, "malloc failed");
2840     
2841     rewriteconfs = list_create();
2842     if (!rewriteconfs)
2843         debugx(1, DBG_ERR, "malloc failed");    
2844  
2845     getgenericconfig(&cfs, NULL,
2846                      "ListenUDP", CONF_STR, &options.listenudp,
2847                      "ListenTCP", CONF_STR, &options.listentcp,
2848                      "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
2849                      "SourceUDP", CONF_STR, &options.sourceudp,
2850                      "SourceTCP", CONF_STR, &options.sourcetcp,
2851                      "LogLevel", CONF_STR, &loglevel,
2852                      "LogDestination", CONF_STR, &options.logdestination,
2853                      "Client", CONF_CBK, confclient_cb,
2854                      "Server", CONF_CBK, confserver_cb,
2855                      "Realm", CONF_CBK, confrealm_cb,
2856                      "TLS", CONF_CBK, conftls_cb,
2857                      "Rewrite", CONF_CBK, confrewrite_cb,
2858                      NULL
2859                      );
2860     popgconffile(&cfs);
2861     tlsfree();
2862     rewritefree();
2863     
2864     if (loglevel) {
2865         if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
2866             debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
2867         options.loglevel = *loglevel - '0';
2868         free(loglevel);
2869     }
2870 }
2871
2872 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
2873     int c;
2874
2875     while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
2876         switch (c) {
2877         case 'c':
2878             *configfile = optarg;
2879             break;
2880         case 'd':
2881             if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
2882                 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
2883             *loglevel = *optarg - '0';
2884             break;
2885         case 'f':
2886             *foreground = 1;
2887             break;
2888         case 'p':
2889             *pretend = 1;
2890             break;
2891         case 'v':
2892                 debugx(0, DBG_ERR, "radsecproxy 1.1-alpha");
2893         default:
2894             goto usage;
2895         }
2896     }
2897     if (!(argc - optind))
2898         return;
2899
2900  usage:
2901     debug(DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
2902     exit(1);
2903 }
2904
2905 #ifdef SYS_SOLARIS9
2906 int daemon(int a, int b) {
2907     int i;
2908
2909     if (fork())
2910         exit(0);
2911
2912     setsid();
2913
2914     for (i = 0; i < 3; i++) {
2915         close(i);
2916         open("/dev/null", O_RDWR);
2917     }
2918     return 1;
2919 }
2920 #endif
2921
2922 int main(int argc, char **argv) {
2923     pthread_t udpserverth, udpaccserverth, udpclient4rdth, udpclient6rdth;
2924     struct list_node *entry;
2925     uint8_t foreground = 0, pretend = 0, loglevel = 0;
2926     char *configfile = NULL;
2927     
2928     debug_init("radsecproxy");
2929     debug_set_level(DEBUG_LEVEL);
2930     getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
2931     if (loglevel)
2932         debug_set_level(loglevel);
2933     getmainconfig(configfile ? configfile : CONFIG_MAIN);
2934     if (loglevel)
2935         options.loglevel = loglevel;
2936     else if (options.loglevel)
2937         debug_set_level(options.loglevel);
2938     if (foreground)
2939         options.logdestination = NULL;
2940     else {
2941         if (!options.logdestination)
2942             options.logdestination = "x-syslog:///";
2943         debug_set_destination(options.logdestination);
2944     }
2945
2946     if (pretend)
2947         debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
2948     
2949     if (!list_first(clconfs))
2950         debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
2951     if (!list_first(srvconfs))
2952         debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
2953     if (!list_first(realms))
2954         debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
2955
2956     if (!foreground && (daemon(0, 0) < 0))
2957         debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
2958     
2959     debug(DBG_INFO, "radsecproxy 1.1-alpha starting");
2960
2961     if (client_udp_count) {
2962         udp_server_replyq = newreplyq();
2963         if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
2964             debugx(1, DBG_ERR, "pthread_create failed");
2965         if (options.listenaccudp)
2966             if (pthread_create(&udpaccserverth, NULL, udpaccserverrd, NULL))
2967                 debugx(1, DBG_ERR, "pthread_create failed");
2968     }
2969     
2970     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2971         addserver((struct clsrvconf *)entry->data);
2972         if (pthread_create(&((struct clsrvconf *)entry->data)->servers->clientth, NULL, clientwr,
2973                            (void *)((struct clsrvconf *)entry->data)->servers))
2974             debugx(1, DBG_ERR, "pthread_create failed");
2975     }
2976     /* srcudpres no longer needed, while srctcpres is needed later */
2977     if (srcudpres) {
2978         free(srcudpres);
2979         srcudpres = NULL;
2980     }
2981     if (udp_client4_sock >= 0)
2982         if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
2983             debugx(1, DBG_ERR, "clientwr: pthread_create failed");
2984     if (udp_client6_sock >= 0)
2985         if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
2986             debugx(1, DBG_ERR, "clientwr: pthread_create failed");
2987     
2988     if (client_tls_count)
2989         return tlslistener();
2990     
2991     /* just hang around doing nothing, anything to do here? */
2992     for (;;)
2993         sleep(1000);
2994 }