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"
30 #include "../patricianick/patricianick.h"
35 static int countext
, enforcepolicy_irc
, enforcepolicy_auth
;
37 #define TRUSTBUFSIZE 8192
38 #define TRUSTPASSLEN 128
41 typedef struct trustsocket
{
44 char authuser
[SERVERLEN
+1];
45 char buf
[TRUSTBUFSIZE
];
46 unsigned char nonce
[NONCELEN
];
53 struct trustsocket
*next
;
56 static trustsocket
*tslist
;
57 static int listenerfd
= -1;
60 typedef struct trustaccount
{
62 char server
[SERVERLEN
+1];
63 char password
[TRUSTPASSLEN
+1];
66 trustaccount trustaccounts
[MAXSERVERS
];
68 static int checkconnection(const char *username
, struct irc_in_addr
*ipaddress
, int hooknum
, int usercountadjustment
, char *message
, size_t messagelen
, int *unthrottle
) {
71 struct irc_in_addr ipaddress_canonical
;
73 ip_canonicalize_tunnel(&ipaddress_canonical
, ipaddress
);
75 th
= th_getbyhost(&ipaddress_canonical
);
83 if(!th
|| !trustsdbloaded
|| irc_in_addr_is_loopback(ipaddress
))
84 return POLICY_SUCCESS
;
89 * the purpose of this logic is to avoid spam like this:
90 * WARNING: tgX exceeded limit: 11 connected vs 10 max
91 * (goes back down to 10)
92 * WARNING: tgX exceeded limit: 11 connected vs 10 max
95 if(hooknum
== HOOK_TRUSTS_NEWNICK
) {
96 patricia_node_t
*head
, *node
;
101 head
= refnode(iptree
, &ipaddress_canonical
, th
->nodebits
);
102 nodecount
= head
->usercount
;
104 /* Account for borrowed IP addresses. */
105 PATRICIA_WALK(head
, node
) {
106 pnp
= node
->exts
[pnode_ext
];
109 for (i
= 0; i
< PATRICIANICK_HASHSIZE
; i
++)
110 for (npp
= pnp
->identhash
[i
]; npp
; npp
=npp
->exts
[pnick_ext
])
111 if (NickOnServiceServer(npp
))
112 usercountadjustment
--;
116 derefnode(iptree
, head
);
118 if(th
->maxpernode
&& nodecount
+ usercountadjustment
> th
->maxpernode
) {
119 controlwall(NO_OPER
, NL_CLONING
, "Hard connection limit exceeded on subnet: %s (group: %s): %d connected, %d max.", CIDRtostr(*ipaddress
, th
->nodebits
), tg
->name
->content
, nodecount
+ usercountadjustment
, th
->maxpernode
);
120 snprintf(message
, messagelen
, "Too many connections from your host (%s) - see https://www.quakenet.org/help/trusts/connection-limit for details.", IPtostr(*ipaddress
));
121 return POLICY_FAILURE_NODECOUNT
;
124 if(tg
->trustedfor
&& tg
->count
+ usercountadjustment
> tg
->trustedfor
) {
125 if(tg
->count
> (long)tg
->exts
[countext
]) {
126 tg
->exts
[countext
] = (void *)(long)tg
->count
;
128 controlwall(NO_OPER
, NL_CLONING
, "Hard connection limit exceeded (group %s): %d connected, %d max.", tg
->name
->content
, tg
->count
+ usercountadjustment
, tg
->trustedfor
);
129 snprintf(message
, messagelen
, "Too many connections from your trust (%s) - see https://www.quakenet.org/help/trusts/connection-limit for details.", IPtostr(*ipaddress
));
132 snprintf(message
, messagelen
, "Too many connections from your trust (%s) - see https://www.quakenet.org/help/trusts/connection-limit for details.", IPtostr(*ipaddress
));
133 return POLICY_FAILURE_GROUPCOUNT
;
136 if((tg
->flags
& TRUST_ENFORCE_IDENT
) && (username
[0] == '~')) {
137 controlwall(NO_OPER
, NL_CLONING
, "Ident required: %s@%s (group: %s).", username
, IPtostr(*ipaddress
), tg
->name
->content
);
138 snprintf(message
, messagelen
, "IDENTD required from your host (%s) - see https://www.quakenet.org/help/trusts/connection-limit for details.", IPtostr(*ipaddress
));
139 return POLICY_FAILURE_IDENTD
;
142 if(tg
->maxperident
> 0) {
147 for(th2
=tg
->hosts
;th2
;th2
=th2
->next
) {
148 for(tnp
=th2
->users
;tnp
;tnp
=nextbytrust(tnp
)) {
149 if(!ircd_strcmp(tnp
->ident
, username
))
154 if(identcount
+ usercountadjustment
> tg
->maxperident
) {
155 controlwall(NO_OPER
, NL_CLONING
, "Hard ident limit exceeded: %s@%s (group: %s): %d connected, %d max.", username
, IPtostr(*ipaddress
), tg
->name
->content
, identcount
+ usercountadjustment
, tg
->maxperident
);
156 snprintf(message
, messagelen
, "Too many connections from your username (%s@%s) - see https://www.quakenet.org/help/trusts/connection-limit for details.", username
, IPtostr(*ipaddress
));
157 return POLICY_FAILURE_IDENTCOUNT
;
161 if(tg
->count
< tg
->maxusage
)
162 tg
->exts
[countext
] = (void *)(long)tg
->count
;
165 if(tg
->trustedfor
> 0)
166 snprintf(message
, messagelen
, "Trust has %d out of %d allowed connections.", tg
->count
+ usercountadjustment
, tg
->trustedfor
);
168 if(unthrottle
&& (tg
->flags
& TRUST_UNTHROTTLE
))
169 *unthrottle
= 1; /* TODO: Do _some_ kind of rate-limiting */
171 return POLICY_SUCCESS
;
174 static int trustdowrite(trustsocket
*sock
, char *format
, ...) {
179 va_start(va
, format
);
180 r
= vsnprintf(buf
, sizeof(buf
), format
, va
);
188 if(write(sock
->fd
, buf
, r
+ 1) != r
+ 1)
193 static int policycheck_auth(trustsocket
*sock
, const char *sequence_id
, const char *username
, const char *host
) {
195 int verdict
, unthrottle
;
196 struct irc_in_addr ipaddress
;
200 if(!ipmask_parse(host
, &ipaddress
, &bits
)) {
202 return trustdowrite(sock
, "PASS %s", sequence_id
);
205 verdict
= checkconnection(username
, &ipaddress
, HOOK_TRUSTS_NEWNICK
, 1, message
, sizeof(message
), &unthrottle
);
207 if(!enforcepolicy_auth
)
208 verdict
= POLICY_SUCCESS
;
210 if (verdict
== POLICY_SUCCESS
) {
214 for (ts
= tslist
; ts
; ts
= ts
->next
)
215 trustdowrite(ts
, "UNTHROTTLE %s", IPtostr(ipaddress
));
219 return trustdowrite(sock
, "PASS %s %s", sequence_id
, message
);
221 return trustdowrite(sock
, "PASS %s", sequence_id
);
225 controlwall(NO_OPER
, NL_CLONING
, "Rejected connection from %s@%s using IAuth: %s", username
, host
, message
);
226 return trustdowrite(sock
, "KILL %s %s", sequence_id
, message
);
230 static int trustkillconnection(trustsocket
*sock
, char *reason
) {
231 trustdowrite(sock
, "QUIT %s", reason
);
235 static void trustfreeconnection(trustsocket
*sock
, int unlink
) {
236 trustsocket
**pnext
, *ts
;
239 controlwall(NO_OPER
, NL_TRUSTS
, "Lost connection on policy socket for '%s'.", sock
->authed
?sock
->authuser
:"<unauthenticated connection>");
241 deregisterhandler(sock
->fd
, 1);
242 nsfree(POOL_TRUSTS
, sock
);
248 for(ts
=*pnext
;*pnext
;pnext
=&((*pnext
)->next
)) {
251 trustfreeconnection(sock
, 0);
257 static int handletrustauth(trustsocket
*sock
, char *server_name
, char *mac
) {
259 char *password
= NULL
;
260 unsigned char digest
[16];
261 char noncehexbuf
[NONCELEN
* 2 + 1];
262 char hexbuf
[sizeof(digest
) * 2 + 1];
264 for(i
=0;i
<MAXSERVERS
;i
++) {
265 if(trustaccounts
[i
].used
&& strcmp(trustaccounts
[i
].server
, server_name
) == 0) {
266 password
= trustaccounts
[i
].password
;
272 controlwall(NO_OPER
, NL_TRUSTS
, "Invalid servername for policy socket: '%s'", server_name
);
273 return trustkillconnection(sock
, "Invalid servername.");
277 hmacmd5_init(&h
, (unsigned char *)password
, strlen(password
));
278 hmacmd5_update(&h
, (unsigned char *)hmac_printhex(sock
->nonce
, noncehexbuf
, NONCELEN
), NONCELEN
* 2);
279 hmacmd5_final(&h
, digest
);
280 if(hmac_strcmp(mac
, hmac_printhex(digest
, hexbuf
, sizeof(digest
)))) {
281 controlwall(NO_OPER
, NL_TRUSTS
, "Invalid password for policy socket with servername '%s'.", server_name
);
282 return trustkillconnection(sock
, "Bad MAC.");
286 strncpy(sock
->authuser
, server_name
, SERVERLEN
);
288 controlwall(NO_OPER
, NL_TRUSTS
, "Successful authentication for policy socket with servername '%s'.", server_name
);
289 return trustdowrite(sock
, "AUTHOK");
293 static int handletrustline(trustsocket
*sock
, char *line
) {
294 char *command
, *p
, *lastpos
;
295 char *tokens
[MAXTOKENS
];
296 int tokensfound
= -1;
298 for(command
=lastpos
=p
=line
;*p
;p
++) {
301 if(tokensfound
== MAXTOKENS
)
302 return trustkillconnection(sock
, "too many tokens");
304 if(tokensfound
>= 0) {
305 tokens
[tokensfound
++] = lastpos
;
313 if(tokensfound
== MAXTOKENS
)
314 return trustkillconnection(sock
, "too many tokens");
315 tokens
[tokensfound
++] = lastpos
;
318 if(!sock
->authed
&& !strcmp("AUTH", command
)) {
320 return trustkillconnection(sock
, "incorrect arg count for command.");
322 return handletrustauth(sock
, tokens
[0], tokens
[1]);
323 } else if(sock
->authed
&& !strcmp("CHECK", command
)) {
325 return trustkillconnection(sock
, "incorrect arg count for command.");
327 policycheck_auth(sock
, tokens
[0], tokens
[1], tokens
[2]);
329 } else if(!strcmp("VERSION", command
)) {
330 /* Ignore this command for now. */
333 Error("trusts_policy", ERR_WARNING
, "Bad command: %s", command
);
338 static trustsocket
*findtrustsocketbyfd(int fd
) {
339 for(trustsocket
*ts
=tslist
;ts
;ts
=ts
->next
)
346 static int handletrustclient(trustsocket
*sock
) {
347 int r
, remaining
= TRUSTBUFSIZE
- sock
->size
, i
;
351 trustkillconnection(sock
, "Buffer overflow.");
355 r
= read(sock
->fd
, sock
->buf
+ sock
->size
, remaining
);
362 for(c
=sock
->buf
,i
=0;i
<sock
->size
;i
++,c
++) {
366 if(!handletrustline(sock
, lastpos
))
369 lastpos
= c
+ 1; /* is this ok? */
371 sock
->size
-=lastpos
- sock
->buf
;
372 memmove(sock
->buf
, lastpos
, sock
->size
);
377 static void processtrustclient(int fd
, short events
) {
378 trustsocket
*sock
= findtrustsocketbyfd(fd
);
383 if (events
& (POLLPRI
| POLLERR
| POLLHUP
| POLLNVAL
)) {
384 trustfreeconnection(sock
, 1);
389 if(!handletrustclient(sock
))
390 trustfreeconnection(sock
, 1);
393 static void trustdotimeout(void *arg
) {
394 time_t t
= time(NULL
);
395 trustsocket
**pnext
, *sock
;
399 for(sock
=*pnext
;*pnext
;pnext
=&((*pnext
)->next
)) {
400 if(!sock
->authed
&& t
>= sock
->timeout
) {
401 trustkillconnection(sock
, "Auth timeout.");
403 trustfreeconnection(sock
, 0);
408 static void processtrustlistener(int fd
, short events
) {
409 if(events
& POLLIN
) {
411 char buf
[NONCELEN
* 2 + 1];
413 int newfd
= accept(fd
, NULL
, NULL
), flags
;
417 flags
= fcntl(newfd
, F_GETFL
, 0);
419 Error("trusts_policy", ERR_WARNING
, "Unable to set socket non-blocking.");
424 if(fcntl(fd
, F_SETFL
, flags
|O_NONBLOCK
) < 0) {
425 Error("trusts_policy", ERR_WARNING
, "Unable to set socket non-blocking.");
430 registerhandler(newfd
, POLLIN
|POLLERR
|POLLHUP
, processtrustclient
);
432 sock
= nsmalloc(POOL_TRUSTS
, sizeof(trustsocket
));
434 deregisterhandler(newfd
, 1);
442 if(fread((char *)sock
->nonce
, 1, NONCELEN
, urandom
) != NONCELEN
) {
443 Error("trusts_policy", ERR_WARNING
, "Error getting random bytes.");
444 deregisterhandler(newfd
, 1);
446 nsfree(POOL_TRUSTS
, sock
);
450 sock
->connected
= time(NULL
);
451 sock
->timeout
= time(NULL
) + 30;
454 if(!trustdowrite(sock
, "AUTH %s", hmac_printhex(sock
->nonce
, buf
, NONCELEN
))) {
455 Error("trusts_policy", ERR_WARNING
, "Error writing auth to fd %d.", newfd
);
456 deregisterhandler(newfd
, 1);
458 nsfree(POOL_TRUSTS
, sock
);
465 static int createlistenersock(int port
) {
466 struct sockaddr_in s
;
470 memset(&s
, 0, sizeof(struct sockaddr_in
));
471 s
.sin_family
= AF_INET
;
472 s
.sin_addr
.s_addr
= INADDR_ANY
;
473 s
.sin_port
= htons(port
);
475 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
477 Error("trusts_policy", ERR_WARNING
, "Unable to get socket for trustfd.");
482 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof(optval
));
484 if(bind(fd
, (struct sockaddr
*)&s
, sizeof(struct sockaddr_in
)) < 0) {
485 Error("trusts_policy", ERR_WARNING
, "Unable to bind trustfd.");
490 if(listen(fd
, 5) < 0) {
491 Error("trusts_policy", ERR_WARNING
, "Unable to listen on trustfd.");
496 registerhandler(fd
, POLLIN
, processtrustlistener
);
501 static void policycheck_irc(int hooknum
, void *arg
) {
504 long moving
= (long)args
[1];
506 int verdict
, unthrottle
;
512 verdict
= checkconnection(np
->ident
, &np
->ipaddress
, hooknum
, 0, message
, sizeof(message
), &unthrottle
);
514 if(!enforcepolicy_irc
)
515 verdict
= POLICY_SUCCESS
;
518 case POLICY_FAILURE_NODECOUNT
:
519 glinebynick(np
, POLICY_GLINE_DURATION
, message
, GLINE_IGNORE_TRUST
, "trusts_policy");
521 case POLICY_FAILURE_IDENTD
:
522 glinebyip("~*", &np
->ipaddress
, 128, POLICY_GLINE_DURATION
, message
, GLINE_ALWAYS_USER
|GLINE_IGNORE_TRUST
, "trusts_policy");
524 case POLICY_FAILURE_IDENTCOUNT
:
525 glinebynick(np
, POLICY_GLINE_DURATION
, message
, GLINE_ALWAYS_USER
|GLINE_IGNORE_TRUST
, "trusts_policy");
529 if (unthrottle
&& hooknum
== HOOK_NICK_LOSTNICK
&& np
->timestamp
> getnettime() - TRUST_MIN_TIME_RETHROTTLE
) {
530 for (ts
= tslist
; ts
; ts
= ts
->next
)
531 trustdowrite(ts
, "THROTTLE %s", IPtostr(np
->ipaddress
));
535 static int trusts_cmdtrustpolicyirc(void *source
, int cargc
, char **cargv
) {
536 nick
*sender
= source
;
539 controlreply(sender
, "Use of glines for trust policy enforcement is currently %s.", enforcepolicy_irc
?"enabled":"disabled");
543 enforcepolicy_irc
= atoi(cargv
[0]);
544 controlwall(NO_OPER
, NL_TRUSTS
, "%s %s use of glines for trust policy enforcement.", controlid(sender
), enforcepolicy_irc
?"enabled":"disabled");
545 controlreply(sender
, "Use of glines for trust policy enforcement is now %s.", enforcepolicy_irc
?"enabled":"disabled");
550 static int trusts_cmdtrustpolicyauth(void *source
, int cargc
, char **cargv
) {
551 nick
*sender
= source
;
554 controlreply(sender
, "Trust policy enforcement with IAuth is currently %s.", enforcepolicy_auth
?"enabled":"disabled");
558 enforcepolicy_auth
= atoi(cargv
[0]);
559 controlwall(NO_OPER
, NL_TRUSTS
, "%s %s trust policy enforcement with IAuth.", controlid(sender
), enforcepolicy_auth
?"enabled":"disabled");
560 controlreply(sender
, "Trust policy enforcement with IAuth is now %s.", enforcepolicy_auth
?"enabled":"disabled");
566 static int trusts_cmdtrustsockets(void *source
, int cargc
, char **cargv
) {
567 nick
*sender
= source
;
573 controlreply(sender
, "Server Connected for Accepted Rejected");
575 for(sock
=tslist
;sock
;sock
=sock
->next
)
576 controlreply(sender
, "%-35s %-20s %-15d %-15d", sock
->authed
?sock
->authuser
:"<unauthenticated connection>", longtoduration(now
- sock
->connected
, 0), sock
->accepted
, sock
->rejected
);
578 controlreply(sender
, "-- End of list.");
582 void loadtrustaccounts(void) {
585 memset(trustaccounts
, 0, sizeof(trustaccounts
));
587 accts
= getconfigitems("trusts_policy", "server");
589 Error("trusts_policy", ERR_INFO
, "No servers added.");
591 sstring
**servers
= (sstring
**)(accts
->content
);
593 for(i
=0;i
<accts
->cursi
;i
++) {
598 Error("trusts_policy", ERR_INFO
, "Too many servers specified.");
602 strncpy(server
, servers
[i
]->content
, sizeof(server
));
604 pos
= strchr(server
, ',');
607 Error("trusts_policy", ERR_INFO
, "Server line is missing password: %s", server
);
613 trustaccounts
[i
].used
= 1;
614 strncpy(trustaccounts
[i
].server
, server
, SERVERLEN
);
615 strncpy(trustaccounts
[i
].password
, pos
+1, TRUSTPASSLEN
);
620 static void trustaccounts_rehash(int hooknum
, void *arg
) {
628 countext
= registertgext("count");
632 m
= getconfigitem("trusts_policy", "enforcepolicy_irc");
634 enforcepolicy_irc
= atoi(m
->content
);
636 m
= getconfigitem("trusts_policy", "enforcepolicy_auth");
638 enforcepolicy_auth
= atoi(m
->content
);
640 m
= getconfigitem("trusts_policy", "trustport");
642 trustport
= atoi(m
->content
);
644 trustport
= DEFAULT_TRUSTPORT
;
647 listenerfd
= createlistenersock(trustport
);
651 registerhook(HOOK_TRUSTS_NEWNICK
, policycheck_irc
);
652 registerhook(HOOK_TRUSTS_LOSTNICK
, &policycheck_irc
);
653 registerhook(HOOK_CORE_REHASH
, trustaccounts_rehash
);
655 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.");
656 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.");
657 registercontrolhelpcmd("trustsockets", NO_DEVELOPER
, 0, trusts_cmdtrustsockets
, "Usage: trustsockets\nLists all currently active TRUST sockets.");
659 schedulerecurring(time(NULL
)+1, 0, 5, trustdotimeout
, NULL
);
661 urandom
= fopen("/dev/urandom", "rb");
663 Error("trusts_policy", ERR_ERROR
, "Couldn't open /dev/urandom.");
667 trustsocket
*sock
, *next
;
672 releasetgext(countext
);
674 deregisterhook(HOOK_TRUSTS_NEWNICK
, policycheck_irc
);
675 deregisterhook(HOOK_TRUSTS_LOSTNICK
, policycheck_irc
);
676 deregisterhook(HOOK_CORE_REHASH
, trustaccounts_rehash
);
678 deregistercontrolcmd("trustpolicyirc", trusts_cmdtrustpolicyirc
);
679 deregistercontrolcmd("trustpolicyauth", trusts_cmdtrustpolicyauth
);
680 deregistercontrolcmd("trustsockets", trusts_cmdtrustsockets
);
682 deleteallschedules(trustdotimeout
);
687 if (listenerfd
!= -1)
688 deregisterhandler(listenerfd
, 1);
690 for(sock
=tslist
;sock
;) {
693 trustkillconnection(sock
, "Unloading module.");
694 trustfreeconnection(sock
, 0);