6 #include <sys/socket.h>
7 #include <netinet/in.h>
10 #define __USE_MISC /* inet_aton */
13 #include <arpa/inet.h>
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"
34 static int countext
, enforcepolicy_irc
, enforcepolicy_auth
;
36 #define TRUSTBUFSIZE 8192
37 #define TRUSTPASSLEN 128
40 typedef struct trustsocket
{
43 char authuser
[SERVERLEN
+1];
44 char buf
[TRUSTBUFSIZE
];
45 unsigned char nonce
[NONCELEN
];
52 struct trustsocket
*next
;
55 static trustsocket
*tslist
;
56 static int listenerfd
= -1;
59 typedef struct trustaccount
{
61 char server
[SERVERLEN
+1];
62 char password
[TRUSTPASSLEN
+1];
65 trustaccount trustaccounts
[MAXSERVERS
];
67 static int checkconnectionth(const char *username
, struct irc_in_addr
*ip
, trusthost
*th
, int hooknum
, int usercountadjustment
, char *message
, size_t messagelen
, int *unthrottle
) {
76 if(!th
|| !trustsdbloaded
|| irc_in_addr_is_loopback(ip
))
77 return POLICY_SUCCESS
;
82 * the purpose of this logic is to avoid spam like this:
83 * WARNING: tgX exceeded limit: 11 connected vs 10 max
84 * (goes back down to 10)
85 * WARNING: tgX exceeded limit: 11 connected vs 10 max
88 if(hooknum
== HOOK_TRUSTS_NEWNICK
) {
89 patricia_node_t
*node
;
92 node
= refnode(iptree
, ip
, th
->nodebits
);
93 nodecount
= node
->usercount
;
94 derefnode(iptree
, node
);
96 if(th
->maxpernode
&& nodecount
+ usercountadjustment
> th
->maxpernode
) {
97 controlwall(NO_OPER
, NL_CLONING
, "Hard connection limit exceeded on subnet: %s (group: %s): %d connected, %d max.", CIDRtostr(*ip
, th
->nodebits
), tg
->name
->content
, nodecount
+ usercountadjustment
, th
->maxpernode
);
98 snprintf(message
, messagelen
, "Too many connections from your host (%s) - see https://www.quakenet.org/help/trusts/connection-limit for details.", IPtostr(*ip
));
99 return POLICY_FAILURE_NODECOUNT
;
102 if(tg
->trustedfor
&& tg
->count
+ usercountadjustment
> tg
->trustedfor
) {
103 if(tg
->count
> (long)tg
->exts
[countext
]) {
104 tg
->exts
[countext
] = (void *)(long)tg
->count
;
106 controlwall(NO_OPER
, NL_CLONING
, "Hard connection limit exceeded (group %s): %d connected, %d max.", tg
->name
->content
, tg
->count
+ usercountadjustment
, tg
->trustedfor
);
107 snprintf(message
, messagelen
, "Too many connections from your trust (%s) - see https://www.quakenet.org/help/trusts/connection-limit for details.", IPtostr(*ip
));
110 snprintf(message
, messagelen
, "Too many connections from your trust (%s) - see https://www.quakenet.org/help/trusts/connection-limit for details.", IPtostr(*ip
));
111 return POLICY_FAILURE_GROUPCOUNT
;
114 if((tg
->flags
& TRUST_ENFORCE_IDENT
) && (username
[0] == '~')) {
115 controlwall(NO_OPER
, NL_CLONING
, "Ident required: %s@%s (group: %s).", username
, IPtostr(*ip
), tg
->name
->content
);
116 snprintf(message
, messagelen
, "IDENTD required from your host (%s) - see https://www.quakenet.org/help/trusts/connection-limit for details.", IPtostr(*ip
));
117 return POLICY_FAILURE_IDENTD
;
120 if(tg
->maxperident
> 0) {
125 for(th2
=tg
->hosts
;th2
;th2
=th2
->next
) {
126 for(tnp
=th2
->users
;tnp
;tnp
=nextbytrust(tnp
)) {
127 if(!ircd_strcmp(tnp
->ident
, username
))
132 if(identcount
+ usercountadjustment
> tg
->maxperident
) {
133 controlwall(NO_OPER
, NL_CLONING
, "Hard ident limit exceeded: %s@%s (group: %s): %d connected, %d max.", username
, IPtostr(*ip
), tg
->name
->content
, identcount
+ usercountadjustment
, tg
->maxperident
);
134 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
));
135 return POLICY_FAILURE_IDENTCOUNT
;
139 if(tg
->count
< tg
->maxusage
)
140 tg
->exts
[countext
] = (void *)(long)tg
->count
;
143 if(tg
->trustedfor
> 0)
144 snprintf(message
, messagelen
, "Trust has %d out of %d allowed connections.", tg
->count
+ usercountadjustment
, tg
->trustedfor
);
146 if(unthrottle
&& (tg
->flags
& TRUST_UNTHROTTLE
))
147 *unthrottle
= 1; /* TODO: Do _some_ kind of rate-limiting */
149 return POLICY_SUCCESS
;
152 static int trustdowrite(trustsocket
*sock
, char *format
, ...) {
157 va_start(va
, format
);
158 r
= vsnprintf(buf
, sizeof(buf
), format
, va
);
166 if(write(sock
->fd
, buf
, r
+ 1) != r
+ 1)
171 static int policycheck_auth(trustsocket
*sock
, const char *sequence_id
, const char *username
, const char *host
) {
173 int verdict
, unthrottle
;
174 struct irc_in_addr ip
, ip_canonicalized
;
178 if(!ipmask_parse(host
, &ip
, &bits
)) {
180 return trustdowrite(sock
, "PASS %s", sequence_id
);
183 ip_canonicalize_tunnel(&ip_canonicalized
, &ip
);
184 verdict
= checkconnectionth(username
, &ip_canonicalized
, th_getbyhost(&ip_canonicalized
), HOOK_TRUSTS_NEWNICK
, 1, message
, sizeof(message
), &unthrottle
);
186 if(!enforcepolicy_auth
)
187 verdict
= POLICY_SUCCESS
;
189 if (verdict
== POLICY_SUCCESS
) {
193 for (ts
= tslist
; ts
; ts
= ts
->next
)
194 trustdowrite(ts
, "UNTHROTTLE %s", IPtostr(ip
));
198 return trustdowrite(sock
, "PASS %s %s", sequence_id
, message
);
200 return trustdowrite(sock
, "PASS %s", sequence_id
);
204 controlwall(NO_OPER
, NL_CLONING
, "Rejected connection from %s@%s using IAuth: %s", username
, host
, message
);
205 return trustdowrite(sock
, "KILL %s %s", sequence_id
, message
);
209 static int trustkillconnection(trustsocket
*sock
, char *reason
) {
210 trustdowrite(sock
, "QUIT %s", reason
);
214 static void trustfreeconnection(trustsocket
*sock
, int unlink
) {
215 trustsocket
**pnext
, *ts
;
218 controlwall(NO_OPER
, NL_TRUSTS
, "Lost connection on policy socket for '%s'.", sock
->authed
?sock
->authuser
:"<unauthenticated connection>");
220 deregisterhandler(sock
->fd
, 1);
221 nsfree(POOL_TRUSTS
, sock
);
227 for(ts
=*pnext
;*pnext
;pnext
=&((*pnext
)->next
)) {
230 trustfreeconnection(sock
, 0);
236 static int handletrustauth(trustsocket
*sock
, char *server_name
, char *mac
) {
238 char *password
= NULL
;
239 unsigned char digest
[16];
240 char noncehexbuf
[NONCELEN
* 2 + 1];
241 char hexbuf
[sizeof(digest
) * 2 + 1];
243 for(i
=0;i
<MAXSERVERS
;i
++) {
244 if(trustaccounts
[i
].used
&& strcmp(trustaccounts
[i
].server
, server_name
) == 0) {
245 password
= trustaccounts
[i
].password
;
251 controlwall(NO_OPER
, NL_TRUSTS
, "Invalid servername for policy socket: '%s'", server_name
);
252 return trustkillconnection(sock
, "Invalid servername.");
256 hmacmd5_init(&h
, (unsigned char *)password
, strlen(password
));
257 hmacmd5_update(&h
, (unsigned char *)hmac_printhex(sock
->nonce
, noncehexbuf
, NONCELEN
), NONCELEN
* 2);
258 hmacmd5_final(&h
, digest
);
259 if(hmac_strcmp(mac
, hmac_printhex(digest
, hexbuf
, sizeof(digest
)))) {
260 controlwall(NO_OPER
, NL_TRUSTS
, "Invalid password for policy socket with servername '%s'.", server_name
);
261 return trustkillconnection(sock
, "Bad MAC.");
265 strncpy(sock
->authuser
, server_name
, SERVERLEN
);
267 controlwall(NO_OPER
, NL_TRUSTS
, "Successful authentication for policy socket with servername '%s'.", server_name
);
268 return trustdowrite(sock
, "AUTHOK");
272 static int handletrustline(trustsocket
*sock
, char *line
) {
273 char *command
, *p
, *lastpos
;
274 char *tokens
[MAXTOKENS
];
275 int tokensfound
= -1;
277 for(command
=lastpos
=p
=line
;*p
;p
++) {
280 if(tokensfound
== MAXTOKENS
)
281 return trustkillconnection(sock
, "too many tokens");
283 if(tokensfound
>= 0) {
284 tokens
[tokensfound
++] = lastpos
;
292 if(tokensfound
== MAXTOKENS
)
293 return trustkillconnection(sock
, "too many tokens");
294 tokens
[tokensfound
++] = lastpos
;
297 if(!sock
->authed
&& !strcmp("AUTH", command
)) {
299 return trustkillconnection(sock
, "incorrect arg count for command.");
301 return handletrustauth(sock
, tokens
[0], tokens
[1]);
302 } else if(sock
->authed
&& !strcmp("CHECK", command
)) {
304 return trustkillconnection(sock
, "incorrect arg count for command.");
306 policycheck_auth(sock
, tokens
[0], tokens
[1], tokens
[2]);
308 } else if(!strcmp("VERSION", command
)) {
309 /* Ignore this command for now. */
312 Error("trusts_policy", ERR_WARNING
, "Bad command: %s", command
);
317 static trustsocket
*findtrustsocketbyfd(int fd
) {
318 for(trustsocket
*ts
=tslist
;ts
;ts
=ts
->next
)
325 static int handletrustclient(trustsocket
*sock
) {
326 int r
, remaining
= TRUSTBUFSIZE
- sock
->size
, i
;
330 trustkillconnection(sock
, "Buffer overflow.");
334 r
= read(sock
->fd
, sock
->buf
+ sock
->size
, remaining
);
341 for(c
=sock
->buf
,i
=0;i
<sock
->size
;i
++,c
++) {
345 if(!handletrustline(sock
, lastpos
))
348 lastpos
= c
+ 1; /* is this ok? */
350 sock
->size
-=lastpos
- sock
->buf
;
351 memmove(sock
->buf
, lastpos
, sock
->size
);
356 static void processtrustclient(int fd
, short events
) {
357 trustsocket
*sock
= findtrustsocketbyfd(fd
);
362 if (events
& (POLLPRI
| POLLERR
| POLLHUP
| POLLNVAL
)) {
363 trustfreeconnection(sock
, 1);
368 if(!handletrustclient(sock
))
369 trustfreeconnection(sock
, 1);
372 static void trustdotimeout(void *arg
) {
373 time_t t
= time(NULL
);
374 trustsocket
**pnext
, *sock
;
378 for(sock
=*pnext
;*pnext
;pnext
=&((*pnext
)->next
)) {
379 if(!sock
->authed
&& t
>= sock
->timeout
) {
380 trustkillconnection(sock
, "Auth timeout.");
382 trustfreeconnection(sock
, 0);
387 static void processtrustlistener(int fd
, short events
) {
388 if(events
& POLLIN
) {
390 char buf
[NONCELEN
* 2 + 1];
392 int newfd
= accept(fd
, NULL
, NULL
), flags
;
396 flags
= fcntl(newfd
, F_GETFL
, 0);
398 Error("trusts_policy", ERR_WARNING
, "Unable to set socket non-blocking.");
403 if(fcntl(fd
, F_SETFL
, flags
|O_NONBLOCK
) < 0) {
404 Error("trusts_policy", ERR_WARNING
, "Unable to set socket non-blocking.");
409 registerhandler(newfd
, POLLIN
|POLLERR
|POLLHUP
, processtrustclient
);
411 sock
= nsmalloc(POOL_TRUSTS
, sizeof(trustsocket
));
413 deregisterhandler(newfd
, 1);
421 if(fread((char *)sock
->nonce
, 1, NONCELEN
, urandom
) != NONCELEN
) {
422 Error("trusts_policy", ERR_WARNING
, "Error getting random bytes.");
423 deregisterhandler(newfd
, 1);
425 nsfree(POOL_TRUSTS
, sock
);
429 sock
->connected
= time(NULL
);
430 sock
->timeout
= time(NULL
) + 30;
433 if(!trustdowrite(sock
, "AUTH %s", hmac_printhex(sock
->nonce
, buf
, NONCELEN
))) {
434 Error("trusts_policy", ERR_WARNING
, "Error writing auth to fd %d.", newfd
);
435 deregisterhandler(newfd
, 1);
437 nsfree(POOL_TRUSTS
, sock
);
444 static int createlistenersock(int port
) {
445 struct sockaddr_in s
;
449 memset(&s
, 0, sizeof(struct sockaddr_in
));
450 s
.sin_family
= AF_INET
;
451 s
.sin_addr
.s_addr
= INADDR_ANY
;
452 s
.sin_port
= htons(port
);
454 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
456 Error("trusts_policy", ERR_WARNING
, "Unable to get socket for trustfd.");
461 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof(optval
));
463 if(bind(fd
, (struct sockaddr
*)&s
, sizeof(struct sockaddr_in
)) < 0) {
464 Error("trusts_policy", ERR_WARNING
, "Unable to bind trustfd.");
469 if(listen(fd
, 5) < 0) {
470 Error("trusts_policy", ERR_WARNING
, "Unable to listen on trustfd.");
475 registerhandler(fd
, POLLIN
, processtrustlistener
);
480 static void policycheck_irc(int hooknum
, void *arg
) {
483 long moving
= (long)args
[1];
485 int verdict
, unthrottle
;
486 struct irc_in_addr ipaddress_canonical
;
492 ip_canonicalize_tunnel(&ipaddress_canonical
, &np
->ipaddress
);
494 verdict
= checkconnectionth(np
->ident
, &ipaddress_canonical
, gettrusthost(np
), hooknum
, 0, message
, sizeof(message
), &unthrottle
);
496 if(!enforcepolicy_irc
)
497 verdict
= POLICY_SUCCESS
;
500 case POLICY_FAILURE_NODECOUNT
:
501 glinebynick(np
, POLICY_GLINE_DURATION
, message
, GLINE_IGNORE_TRUST
, "trusts_policy");
503 case POLICY_FAILURE_IDENTD
:
504 glinebyip("~*", &np
->ipaddress
, 128, POLICY_GLINE_DURATION
, message
, GLINE_ALWAYS_USER
|GLINE_IGNORE_TRUST
, "trusts_policy");
506 case POLICY_FAILURE_IDENTCOUNT
:
507 glinebynick(np
, POLICY_GLINE_DURATION
, message
, GLINE_ALWAYS_USER
|GLINE_IGNORE_TRUST
, "trusts_policy");
511 if (unthrottle
&& hooknum
== HOOK_NICK_LOSTNICK
&& np
->timestamp
> getnettime() - TRUST_MIN_TIME_RETHROTTLE
) {
512 for (ts
= tslist
; ts
; ts
= ts
->next
)
513 trustdowrite(ts
, "THROTTLE %s", IPtostr(np
->ipaddress
));
517 static int trusts_cmdtrustpolicyirc(void *source
, int cargc
, char **cargv
) {
518 nick
*sender
= source
;
521 controlreply(sender
, "Use of glines for trust policy enforcement is currently %s.", enforcepolicy_irc
?"enabled":"disabled");
525 enforcepolicy_irc
= atoi(cargv
[0]);
526 controlwall(NO_OPER
, NL_TRUSTS
, "%s %s use of glines for trust policy enforcement.", controlid(sender
), enforcepolicy_irc
?"enabled":"disabled");
527 controlreply(sender
, "Use of glines for trust policy enforcement is now %s.", enforcepolicy_irc
?"enabled":"disabled");
532 static int trusts_cmdtrustpolicyauth(void *source
, int cargc
, char **cargv
) {
533 nick
*sender
= source
;
536 controlreply(sender
, "Trust policy enforcement with IAuth is currently %s.", enforcepolicy_auth
?"enabled":"disabled");
540 enforcepolicy_auth
= atoi(cargv
[0]);
541 controlwall(NO_OPER
, NL_TRUSTS
, "%s %s trust policy enforcement with IAuth.", controlid(sender
), enforcepolicy_auth
?"enabled":"disabled");
542 controlreply(sender
, "Trust policy enforcement with IAuth is now %s.", enforcepolicy_auth
?"enabled":"disabled");
548 static int trusts_cmdtrustsockets(void *source
, int cargc
, char **cargv
) {
549 nick
*sender
= source
;
555 controlreply(sender
, "Server Connected for Accepted Rejected");
557 for(sock
=tslist
;sock
;sock
=sock
->next
)
558 controlreply(sender
, "%-35s %-20s %-15d %-15d", sock
->authed
?sock
->authuser
:"<unauthenticated connection>", longtoduration(now
- sock
->connected
, 0), sock
->accepted
, sock
->rejected
);
560 controlreply(sender
, "-- End of list.");
564 void loadtrustaccounts(void) {
567 memset(trustaccounts
, 0, sizeof(trustaccounts
));
569 accts
= getconfigitems("trusts_policy", "server");
571 Error("trusts_policy", ERR_INFO
, "No servers added.");
573 sstring
**servers
= (sstring
**)(accts
->content
);
575 for(i
=0;i
<accts
->cursi
;i
++) {
580 Error("trusts_policy", ERR_INFO
, "Too many servers specified.");
584 strncpy(server
, servers
[i
]->content
, sizeof(server
));
586 pos
= strchr(server
, ',');
589 Error("trusts_policy", ERR_INFO
, "Server line is missing password: %s", server
);
595 trustaccounts
[i
].used
= 1;
596 strncpy(trustaccounts
[i
].server
, server
, SERVERLEN
);
597 strncpy(trustaccounts
[i
].password
, pos
+1, TRUSTPASSLEN
);
602 static void trustaccounts_rehash(int hooknum
, void *arg
) {
610 countext
= registertgext("count");
614 m
= getconfigitem("trusts_policy", "enforcepolicy_irc");
616 enforcepolicy_irc
= atoi(m
->content
);
618 m
= getconfigitem("trusts_policy", "enforcepolicy_auth");
620 enforcepolicy_auth
= atoi(m
->content
);
622 m
= getconfigitem("trusts_policy", "trustport");
624 trustport
= atoi(m
->content
);
626 trustport
= DEFAULT_TRUSTPORT
;
629 listenerfd
= createlistenersock(trustport
);
633 registerhook(HOOK_TRUSTS_NEWNICK
, policycheck_irc
);
634 registerhook(HOOK_TRUSTS_LOSTNICK
, &policycheck_irc
);
635 registerhook(HOOK_CORE_REHASH
, trustaccounts_rehash
);
637 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.");
638 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.");
639 registercontrolhelpcmd("trustsockets", NO_DEVELOPER
, 0, trusts_cmdtrustsockets
, "Usage: trustsockets\nLists all currently active TRUST sockets.");
641 schedulerecurring(time(NULL
)+1, 0, 5, trustdotimeout
, NULL
);
643 urandom
= fopen("/dev/urandom", "rb");
645 Error("trusts_policy", ERR_ERROR
, "Couldn't open /dev/urandom.");
649 trustsocket
*sock
, *next
;
654 releasetgext(countext
);
656 deregisterhook(HOOK_TRUSTS_NEWNICK
, policycheck_irc
);
657 deregisterhook(HOOK_TRUSTS_LOSTNICK
, policycheck_irc
);
658 deregisterhook(HOOK_CORE_REHASH
, trustaccounts_rehash
);
660 deregistercontrolcmd("trustpolicyirc", trusts_cmdtrustpolicyirc
);
661 deregistercontrolcmd("trustpolicyauth", trusts_cmdtrustpolicyauth
);
662 deregistercontrolcmd("trustsockets", trusts_cmdtrustsockets
);
664 deleteallschedules(trustdotimeout
);
669 if (listenerfd
!= -1)
670 deregisterhandler(listenerfd
, 1);
672 for(sock
=tslist
;sock
;) {
675 trustkillconnection(sock
, "Unloading module.");
676 trustfreeconnection(sock
, 0);