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