]> jfr.im git - irc/quakenet/newserv.git/blob - trusts/trusts_policy.c
Bugfixes for the trust sockets code.
[irc/quakenet/newserv.git] / trusts / trusts_policy.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <stdarg.h>
4 #include <unistd.h>
5 #include <sys/types.h>
6 #include <sys/socket.h>
7 #include <netinet/in.h>
8
9 #ifndef __USE_MISC
10 #define __USE_MISC /* inet_aton */
11 #endif
12
13 #include <arpa/inet.h>
14 #include <sys/un.h>
15 #include <sys/poll.h>
16 #include <errno.h>
17 #include <fcntl.h>
18
19 #include "../lib/hmac.h"
20 #include "../core/events.h"
21 #include "../core/schedule.h"
22 #include "../core/nsmalloc.h"
23 #include "../core/hooks.h"
24 #include "../core/config.h"
25 #include "../control/control.h"
26 #include "../lib/irc_string.h"
27 #include "../irc/irc.h"
28 #include "../glines/glines.h"
29 #include "trusts.h"
30
31 static int countext, enforcepolicy;
32
33 #define TRUSTBUFSIZE 8192
34 #define TRUSTPASSLEN 128
35 #define NONCELEN 16
36
37 typedef struct trustsocket {
38 int fd;
39 int authed;
40 char authuser[SERVERLEN+1];
41 char buf[TRUSTBUFSIZE];
42 unsigned char nonce[NONCELEN];
43 int size;
44 time_t connected;
45 time_t timeout;
46 int accepted;
47 int rejected;
48
49 struct trustsocket *next;
50 } trustsocket;
51
52 static trustsocket *tslist;
53 static int listenerfd = -1;
54 static FILE *urandom;
55
56 typedef struct trustaccount {
57 int used;
58 char server[SERVERLEN+1];
59 char password[TRUSTPASSLEN+1];
60 } trustaccount;
61
62 trustaccount trustaccounts[MAXSERVERS];
63
64 static int checkconnectionth(const char *username, struct irc_in_addr *ip, trusthost *th, int hooknum, int usercountadjustment, char *message, size_t messagelen, char *hint) {
65 trustgroup *tg;
66
67 if(messagelen>0)
68 message[0] = '\0';
69
70 if(!th)
71 return POLICY_SUCCESS;
72
73 tg = th->group;
74
75 /*
76 * the purpose of this logic is to avoid spam like this:
77 * WARNING: tgX exceeded limit: 11 connected vs 10 max
78 * (goes back down to 10)
79 * WARNING: tgX exceeded limit: 11 connected vs 10 max
80 */
81
82 if(hooknum == HOOK_TRUSTS_NEWNICK) {
83 patricia_node_t *head, *node;
84 int nodecount = 0;
85
86 head = refnode(iptree, ip, th->nodebits);
87 PATRICIA_WALK(head, node)
88 {
89 nodecount += node->usercount;
90 }
91 PATRICIA_WALK_END;
92 derefnode(iptree, head);
93
94 if(th->maxpernode && nodecount + usercountadjustment > th->maxpernode) {
95 controlwall(NO_OPER, NL_TRUSTS, "Hard connection limit exceeded on subnet: %s (group: %s) %d connected, %d max - %s.", trusts_cidr2str(ip, th->nodebits), tg->name->content, nodecount, th->maxpernode, hint);
96 snprintf(message, messagelen, "Too many connections from your host (%s) - see http://www.quakenet.org/help/trusts/connection-limit for details.", IPtostr(*ip));
97 return POLICY_FAILURE_NODECOUNT;
98 }
99
100 if(tg->trustedfor && tg->count + usercountadjustment > tg->trustedfor) {
101 if(tg->count > (long)tg->exts[countext]) {
102 tg->exts[countext] = (void *)(long)tg->count;
103
104 controlwall(NO_OPER, NL_TRUSTS, "Hard connection limit exceeded: '%s', %d connected, %d max. - %s.", tg->name->content, tg->count, tg->trustedfor, hint);
105 snprintf(message, messagelen, "Too many connections from your trust (%s) - see http://www.quakenet.org/help/trusts/connection-limit for details.", IPtostr(*ip));
106 return POLICY_FAILURE_GROUPCOUNT;
107 }
108
109 snprintf(message, messagelen, "Trust has %d out of %d allowed connections.", tg->count + usercountadjustment, tg->trustedfor);
110 }
111
112 if((tg->flags & TRUST_ENFORCE_IDENT) && (username[0] == '~')) {
113 controlwall(NO_OPER, NL_TRUSTS, "Ident required: %s@%s (group: %s) - %s.", username, IPtostr(*ip), tg->name->content, hint);
114 snprintf(message, messagelen, "IDENTD required from your host (%s) - see http://www.quakenet.org/help/trusts/connection-limit for details.", IPtostr(*ip));
115 return POLICY_FAILURE_IDENTD;
116 }
117
118 if(tg->maxperident > 0) {
119 int identcount = 0;
120 trusthost *th2;
121 nick *tnp;
122
123 for(th2=tg->hosts;th2;th2=th2->next) {
124 for(tnp=th2->users;tnp;tnp=nextbytrust(tnp)) {
125 if(!ircd_strcmp(tnp->ident, username))
126 identcount++;
127 }
128 }
129
130 if(identcount + usercountadjustment > tg->maxperident) {
131 controlwall(NO_OPER, NL_TRUSTS, "Hard ident limit exceeded: %s@%s (group: %s), %d connected, %d max - %s.", username, IPtostr(*ip), tg->name->content, identcount, tg->maxperident, hint);
132 snprintf(message, messagelen, "Too many connections from your username (%s@%s) - see http://www.quakenet.org/help/trusts/connection-limit for details.", username, IPtostr(*ip));
133 return POLICY_FAILURE_IDENTCOUNT;
134 }
135 }
136 } else {
137 if(tg->count < tg->maxusage)
138 tg->exts[countext] = (void *)(long)tg->count;
139 }
140
141 return POLICY_SUCCESS;
142 }
143
144 static int checkconnection(const char *username, struct irc_in_addr *ip, int hooknum, int cloneadjustment, char *message, size_t messagelen, char *hint) {
145 struct irc_in_addr ip_canonicalized;
146 ip_canonicalize_tunnel(&ip_canonicalized, ip);
147
148 return checkconnectionth(username, &ip_canonicalized, th_getbyhost(ip), hooknum, cloneadjustment, message, messagelen, hint);
149 }
150
151 static int trustdowrite(trustsocket *sock, char *format, ...) {
152 char buf[1024];
153 va_list va;
154 int r;
155
156 va_start(va, format);
157 r = vsnprintf(buf, sizeof(buf), format, va);
158 va_end(va);
159
160 if(r >= sizeof(buf))
161 r = sizeof(buf) - 1;
162
163 buf[r] = '\n';
164
165 if(write(sock->fd, buf, r + 1) != r + 1)
166 return 0;
167 return 1;
168 }
169
170 static int policycheck_auth(trustsocket *sock, const char *sequence_id, const char *username, const char *host) {
171 char message[512];
172 int verdict;
173 struct irc_in_addr ip;
174 unsigned char bits;
175
176 if(!ipmask_parse(host, &ip, &bits)) {
177 sock->accepted++;
178 return trustdowrite(sock, "PASS %s", sequence_id);
179 }
180
181 verdict = checkconnection(username, &ip, HOOK_TRUSTS_NEWNICK, 1, message, sizeof(message), "enforcing with IAuth");
182
183 if (verdict == POLICY_SUCCESS) {
184 sock->accepted++;
185
186 if(message[0])
187 return trustdowrite(sock, "PASS %s %s", sequence_id, message);
188 else
189 return trustdowrite(sock, "PASS %s", sequence_id);
190 } else {
191 sock->rejected++;
192
193 return trustdowrite(sock, "KILL %s %s", sequence_id, message);
194 }
195 }
196
197 static int trustkillconnection(trustsocket *sock, char *reason) {
198 trustdowrite(sock, "QUIT %s", reason);
199 return 0;
200 }
201
202 static void trustfreeconnection(trustsocket *sock) {
203 trustsocket **pnext = &tslist;
204
205 for(trustsocket *ts=tslist;ts;ts=ts->next) {
206 if(ts == sock) {
207 deregisterhandler(sock->fd, 1);
208 *pnext = sock->next;
209 nsfree(POOL_TRUSTS, sock);
210 break;
211 }
212
213 pnext = &(sock->next);
214 }
215 }
216
217 static int handletrustauth(trustsocket *sock, char *server_name, char *mac) {
218 int i;
219 char *password = NULL;
220 unsigned char digest[16];
221 char noncehexbuf[NONCELEN * 2 + 1];
222 char hexbuf[sizeof(digest) * 2 + 1];
223
224 for(i=0;i<MAXSERVERS;i++) {
225 if(trustaccounts[i].used && strcmp(trustaccounts[i].server, server_name) == 0) {
226 password = trustaccounts[i].password;
227 break;
228 }
229 }
230
231 if (!password)
232 return trustkillconnection(sock, "Invalid servername.");
233
234 hmacmd5 h;
235 hmacmd5_init(&h, (unsigned char *)password, strlen(password));
236 hmacmd5_update(&h, (unsigned char *)hmac_printhex(sock->nonce, noncehexbuf, NONCELEN), NONCELEN * 2);
237 hmacmd5_final(&h, digest);
238 if(hmac_strcmp(mac, hmac_printhex(digest, hexbuf, sizeof(digest))))
239 return trustkillconnection(sock, "Bad MAC.");
240
241 sock->authed = 1;
242 strncpy(sock->authuser, server_name, SERVERLEN);
243 return trustdowrite(sock, "AUTHOK");
244 }
245
246 #define MAXTOKENS 10
247 static int handletrustline(trustsocket *sock, char *line) {
248 char *command, *p, *lastpos;
249 char *tokens[MAXTOKENS];
250 int tokensfound = -1;
251
252 for(command=lastpos=p=line;*p;p++) {
253 if(*p == ' ') {
254 *p = '\0';
255 if(tokensfound == MAXTOKENS)
256 return trustkillconnection(sock, "too many tokens");
257
258 if(tokensfound >= 0) {
259 tokens[tokensfound++] = lastpos;
260 } else {
261 tokensfound++;
262 }
263 lastpos = p + 1;
264 }
265 }
266 if(lastpos != p) {
267 if(tokensfound == MAXTOKENS)
268 return trustkillconnection(sock, "too many tokens");
269 tokens[tokensfound++] = lastpos;
270 }
271
272 if(!sock->authed && !strcmp("AUTH", command)) {
273 if(tokensfound != 2)
274 return trustkillconnection(sock, "incorrect arg count for command.");
275
276 return handletrustauth(sock, tokens[0], tokens[1]);
277 } else if(sock->authed && !strcmp("CHECK", command)) {
278 if(tokensfound != 3)
279 return trustkillconnection(sock, "incorrect arg count for command.");
280
281 policycheck_auth(sock, tokens[0], tokens[1], tokens[2]);
282 return 1;
283 } else {
284 Error("trusts_policy", ERR_WARNING, "Bad command: %s", command);
285 return 0;
286 }
287 }
288
289 static trustsocket *findtrustsocketbyfd(int fd) {
290 for(trustsocket *ts=tslist;ts;ts=ts->next)
291 if(ts->fd==fd)
292 return ts;
293
294 return NULL;
295 }
296
297 static int handletrustclient(trustsocket *sock) {
298 int r, remaining = TRUSTBUFSIZE - sock->size, i;
299 char *lastpos, *c;
300
301 if(!remaining) {
302 trustkillconnection(sock, "Buffer overflow.");
303 return 0;
304 }
305
306 r = read(sock->fd, sock->buf + sock->size, remaining);
307 if(r <= 0)
308 return 0;
309
310 sock->size+=r;
311 lastpos = sock->buf;
312
313 for(c=sock->buf,i=0;i<sock->size;i++,c++) {
314 if(*c != '\n')
315 continue;
316 *c = '\0';
317 if(!handletrustline(sock, lastpos))
318 return 0;
319
320 lastpos = c + 1; /* is this ok? */
321 }
322 sock->size-=lastpos - sock->buf;
323 memmove(sock->buf, lastpos, sock->size);
324
325 return 1;
326 }
327
328 static void processtrustclient(int fd, short events) {
329 trustsocket *sock = findtrustsocketbyfd(fd);
330
331 if(!sock)
332 return;
333
334 if(events & POLLIN)
335 if(!handletrustclient(sock))
336 trustfreeconnection(sock);
337 }
338
339 static void trustdotimeout(void *arg) {
340 time_t t = time(NULL);
341 trustsocket **pnext, *next, *sock;
342
343 pnext = &tslist;
344
345 for(sock=tslist;sock;) {
346 next = sock->next;
347
348 if(!sock->authed && t >= sock->timeout) {
349 trustkillconnection(sock, "Auth timeout.");
350 deregisterhandler(sock->fd, 1);
351 *pnext = sock->next;
352 nsfree(POOL_TRUSTS, sock);
353 } else {
354 pnext = &(sock->next);
355 }
356
357 sock=next;
358 }
359 }
360
361 static void processtrustlistener(int fd, short events) {
362 if(events & POLLIN) {
363 trustsocket *sock;
364 char buf[NONCELEN * 2 + 1];
365
366 int newfd = accept(fd, NULL, NULL), flags;
367 if(newfd == -1)
368 return;
369
370 flags = fcntl(newfd, F_GETFL, 0);
371 if(flags < 0) {
372 Error("trusts_policy", ERR_WARNING, "Unable to set socket non-blocking.");
373 close(newfd);
374 return;
375 }
376
377 if(fcntl(fd, F_SETFL, flags|O_NONBLOCK) < 0) {
378 Error("trusts_policy", ERR_WARNING, "Unable to set socket non-blocking.");
379 close(newfd);
380 return;
381 }
382
383 registerhandler(newfd, POLLIN|POLLERR|POLLHUP, processtrustclient);
384
385 sock = nsmalloc(POOL_TRUSTS, sizeof(trustsocket));
386 if(!sock) {
387 deregisterhandler(newfd, 1);
388 return;
389 }
390
391 sock->fd = newfd;
392 sock->next = tslist;
393 tslist = sock;
394
395 if(fread((char *)sock->nonce, 1, NONCELEN, urandom) != NONCELEN) {
396 Error("trusts_policy", ERR_WARNING, "Error getting random bytes.");
397 deregisterhandler(newfd, 1);
398 tslist = sock->next;
399 nsfree(POOL_TRUSTS, sock);
400 } else {
401 sock->authed = 0;
402 sock->size = 0;
403 sock->connected = time(NULL);
404 sock->timeout = time(NULL) + 30;
405 sock->accepted = 0;
406 sock->rejected = 0;
407 if(!trustdowrite(sock, "AUTH %s", hmac_printhex(sock->nonce, buf, NONCELEN))) {
408 Error("trusts_policy", ERR_WARNING, "Error writing auth to fd %d.", newfd);
409 deregisterhandler(newfd, 1);
410 tslist = sock->next;
411 nsfree(POOL_TRUSTS, sock);
412 return;
413 }
414 }
415 }
416 }
417
418 static int createlistenersock(int port) {
419 struct sockaddr_in s;
420 int fd;
421 int optval;
422
423 memset(&s, 0, sizeof(struct sockaddr_in));
424 s.sin_family = AF_INET;
425 s.sin_addr.s_addr = INADDR_ANY;
426 s.sin_port = htons(port);
427
428 fd = socket(PF_INET, SOCK_STREAM, 0);
429 if(fd < 0) {
430 Error("trusts_policy", ERR_WARNING, "Unable to get socket for trustfd.");
431 return -1;
432 }
433
434 optval = 1;
435 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
436
437 if(bind(fd, (struct sockaddr *)&s, sizeof(struct sockaddr_in)) < 0) {
438 Error("trusts_policy", ERR_WARNING, "Unable to bind trustfd.");
439 close(fd);
440 return -1;
441 }
442
443 if(listen(fd, 5) < 0) {
444 Error("trusts_policy", ERR_WARNING, "Unable to listen on trustfd.");
445 close(fd);
446 return -1;
447 }
448
449 registerhandler(fd, POLLIN, processtrustlistener);
450
451 return fd;
452 }
453
454 static void policycheck_irc(int hooknum, void *arg) {
455 void **args = arg;
456 nick *np = args[0];
457 long moving = (long)args[1];
458 char message[512];
459 int verdict;
460 char *hint;
461
462 if(moving)
463 return;
464
465 if (enforcepolicy)
466 hint = "enforcing with glines";
467 else
468 hint = "not enforcing";
469
470 verdict = checkconnectionth(np->ident, &np->p_nodeaddr, gettrusthost(np), hooknum, 0, message, sizeof(message), hint);
471
472 if(!enforcepolicy)
473 return;
474
475 switch (verdict) {
476 case POLICY_FAILURE_NODECOUNT:
477 glinebynick(np, POLICY_GLINE_DURATION, message, GLINE_IGNORE_TRUST);
478 break;
479 case POLICY_FAILURE_IDENTD:
480 glinebyip("~*", &np->p_ipaddr, 128, POLICY_GLINE_DURATION, message, GLINE_ALWAYS_USER|GLINE_IGNORE_TRUST);
481 break;
482 case POLICY_FAILURE_IDENTCOUNT:
483 glinebynick(np, POLICY_GLINE_DURATION, message, GLINE_ALWAYS_USER|GLINE_IGNORE_TRUST);
484 break;
485 }
486 }
487
488 static int trusts_cmdtrustpolicy(void *source, int cargc, char **cargv) {
489 nick *sender = source;
490
491 if(cargc < 1) {
492 controlreply(sender, "Trust policy enforcement is currently %s.", enforcepolicy?"enabled":"disabled");
493 return CMD_OK;
494 }
495
496 enforcepolicy = atoi(cargv[0]);
497 controlwall(NO_OPER, NL_TRUSTS, "%s %s trust policy enforcement.", controlid(sender), enforcepolicy?"enabled":"disabled");
498 controlreply(sender, "Trust policy enforcement is now %s.", enforcepolicy?"enabled":"disabled");
499
500 return CMD_OK;
501 }
502
503 static int trusts_cmdtrustsockets(void *source, int cargc, char **cargv) {
504 nick *sender = source;
505 time_t now;
506 trustsocket *sock;
507
508 time(&now);
509
510 controlreply(sender, "Server Connected for Accepted Rejected");
511
512 for(sock=tslist;sock;sock=sock->next)
513 controlreply(sender, "%-20s %20s %10d %15d", sock->authed?sock->authuser:"<not authenticated>", longtoduration(now - sock->connected, 0), sock->accepted, sock->rejected);
514
515 controlreply(sender, "-- End of list.");
516 return CMD_OK;
517 }
518
519 void _init(void) {
520 sstring *m;
521 array *accts;
522 int trustport;
523
524 countext = registertgext("count");
525 if(countext == -1)
526 return;
527
528 m = getconfigitem("trusts_policy", "enforcepolicy");
529 if(m)
530 enforcepolicy = atoi(m->content);
531
532 m = getconfigitem("trusts_policy", "trustport");
533 if(m)
534 trustport = atoi(m->content);
535 else
536 trustport = DEFAULT_TRUSTPORT;
537
538 if(trustport)
539 listenerfd = createlistenersock(trustport);
540
541 accts = getconfigitems("trusts_policy", "server");
542 if(!accts) {
543 Error("trusts_policy", ERR_INFO, "No servers added.");
544 } else {
545 sstring **servers = (sstring **)(accts->content);
546 int i;
547 for(i=0;i<accts->cursi;i++) {
548 char server[512];
549 char *pos;
550
551 if(i>=MAXSERVERS) {
552 Error("trusts_policy", ERR_INFO, "Too many servers specified.");
553 break;
554 }
555
556 strncpy(server, servers[i]->content, sizeof(server));
557
558 pos = strchr(server, ',');
559
560 if(!pos) {
561 Error("trusts_policy", ERR_INFO, "Server line is missing password: %s", server);
562 continue;
563 }
564
565 *pos = '\0';
566
567 trustaccounts[i].used = 1;
568 strncpy(trustaccounts[i].server, server, SERVERLEN);
569 strncpy(trustaccounts[i].password, pos+1, TRUSTPASSLEN);
570 }
571 }
572
573 registerhook(HOOK_TRUSTS_NEWNICK, policycheck_irc);
574 registerhook(HOOK_TRUSTS_LOSTNICK, policycheck_irc);
575
576 registercontrolhelpcmd("trustpolicy", NO_DEVELOPER, 1, trusts_cmdtrustpolicy, "Usage: trustpolicy ?1|0?\nEnables or disables policy enforcement. Shows current status when no parameter is specified.");
577 registercontrolhelpcmd("trustsockets", NO_DEVELOPER, 0, trusts_cmdtrustsockets, "Usage: trustsockets\nLists all currently active TRUST sockets.");
578
579 schedulerecurring(time(NULL)+1, 0, 5, trustdotimeout, NULL);
580
581 urandom = fopen("/dev/urandom", "rb");
582 if(!urandom)
583 Error("trusts_policy", ERR_ERROR, "Couldn't open /dev/urandom.");
584 }
585
586 void _fini(void) {
587 trustsocket *sock, *next;
588
589 if(countext == -1)
590 return;
591
592 releasetgext(countext);
593
594 deregisterhook(HOOK_TRUSTS_NEWNICK, policycheck_irc);
595 deregisterhook(HOOK_TRUSTS_LOSTNICK, policycheck_irc);
596
597 deregistercontrolcmd("trustpolicy", trusts_cmdtrustpolicy);
598 deregistercontrolcmd("trustsockets", trusts_cmdtrustsockets);
599
600 deleteallschedules(trustdotimeout);
601
602 if (urandom)
603 fclose(urandom);
604
605 if (listenerfd != -1)
606 deregisterhandler(listenerfd, 1);
607
608 for(sock=tslist;sock;) {
609 next = sock->next;
610
611 trustkillconnection(sock, "Unloading module.");
612 trustfreeconnection(sock);
613
614 sock = next;
615 }
616 }