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
];
54 struct trustsocket
*next
;
57 static trustsocket
*tslist
;
58 static int listenerfd
= -1;
61 typedef struct trustaccount
{
63 char server
[SERVERLEN
+1];
64 char password
[TRUSTPASSLEN
+1];
67 trustaccount trustaccounts
[MAXSERVERS
];
69 static int checkconnection(const char *username
, struct irc_in_addr
*ipaddress
, int hooknum
, int usercountadjustment
, char *message
, size_t messagelen
, int *unthrottle
) {
72 struct irc_in_addr ipaddress_canonical
;
74 ip_canonicalize_tunnel(&ipaddress_canonical
, ipaddress
);
76 th
= th_getbyhost(&ipaddress_canonical
);
84 if(!th
|| !trustsdbloaded
|| irc_in_addr_is_loopback(ipaddress
))
85 return POLICY_SUCCESS
;
90 * the purpose of this logic is to avoid spam like this:
91 * WARNING: tgX exceeded limit: 11 connected vs 10 max
92 * (goes back down to 10)
93 * WARNING: tgX exceeded limit: 11 connected vs 10 max
96 if(hooknum
== HOOK_TRUSTS_NEWNICK
) {
97 patricia_node_t
*head
, *node
;
102 head
= refnode(iptree
, &ipaddress_canonical
, th
->nodebits
);
103 nodecount
= head
->usercount
;
105 /* Account for borrowed IP addresses. */
106 PATRICIA_WALK(head
, node
) {
107 pnp
= node
->exts
[pnode_ext
];
110 for (i
= 0; i
< PATRICIANICK_HASHSIZE
; i
++)
111 for (npp
= pnp
->identhash
[i
]; npp
; npp
=npp
->exts
[pnick_ext
])
112 if (NickOnServiceServer(npp
))
113 usercountadjustment
--;
117 derefnode(iptree
, head
);
119 if(th
->maxpernode
&& nodecount
+ usercountadjustment
> th
->maxpernode
) {
120 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
);
121 snprintf(message
, messagelen
, "Too many connections from your host (%s) - see https://www.quakenet.org/help/trusts/connection-limit for details.", IPtostr(*ipaddress
));
122 return POLICY_FAILURE_NODECOUNT
;
125 if(tg
->trustedfor
&& tg
->count
+ usercountadjustment
> tg
->trustedfor
) {
126 if(tg
->count
> (long)tg
->exts
[countext
]) {
127 tg
->exts
[countext
] = (void *)(long)tg
->count
;
129 controlwall(NO_OPER
, NL_CLONING
, "Hard connection limit exceeded (group %s): %d connected, %d max.", tg
->name
->content
, tg
->count
+ usercountadjustment
, tg
->trustedfor
);
130 snprintf(message
, messagelen
, "Too many connections from your trust (%s) - see https://www.quakenet.org/help/trusts/connection-limit for details.", IPtostr(*ipaddress
));
133 snprintf(message
, messagelen
, "Too many connections from your trust (%s) - see https://www.quakenet.org/help/trusts/connection-limit for details.", IPtostr(*ipaddress
));
134 return POLICY_FAILURE_GROUPCOUNT
;
137 if((tg
->flags
& TRUST_ENFORCE_IDENT
) && (username
[0] == '~')) {
138 controlwall(NO_OPER
, NL_CLONING
, "Ident required: %s@%s (group: %s).", username
, IPtostr(*ipaddress
), tg
->name
->content
);
139 snprintf(message
, messagelen
, "IDENTD required from your host (%s) - see https://www.quakenet.org/help/trusts/connection-limit for details.", IPtostr(*ipaddress
));
140 return POLICY_FAILURE_IDENTD
;
143 if(tg
->maxperident
> 0) {
148 for(th2
=tg
->hosts
;th2
;th2
=th2
->next
) {
149 for(tnp
=th2
->users
;tnp
;tnp
=nextbytrust(tnp
)) {
150 if(!ircd_strcmp(tnp
->ident
, username
))
155 if(identcount
+ usercountadjustment
> tg
->maxperident
) {
156 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
);
157 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
));
158 return POLICY_FAILURE_IDENTCOUNT
;
162 if(tg
->count
< tg
->maxusage
)
163 tg
->exts
[countext
] = (void *)(long)tg
->count
;
166 if(tg
->trustedfor
> 0)
167 snprintf(message
, messagelen
, "Trust has %d out of %d allowed connections.", tg
->count
+ usercountadjustment
, tg
->trustedfor
);
169 if(unthrottle
&& (tg
->flags
& TRUST_UNTHROTTLE
))
172 return POLICY_SUCCESS
;
175 static int trustdowrite(trustsocket
*sock
, char *format
, ...) {
180 va_start(va
, format
);
181 r
= vsnprintf(buf
, sizeof(buf
), format
, va
);
189 if(write(sock
->fd
, buf
, r
+ 1) != r
+ 1)
194 static int policycheck_auth(trustsocket
*sock
, const char *sequence_id
, const char *username
, const char *host
) {
196 int verdict
, unthrottle
;
197 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
) {
215 trustdowrite(sock
, "UNTHROTTLE %s", sequence_id
);
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
);
246 for(pnext
=&tslist
;*pnext
;pnext
=&((*pnext
)->next
)) {
250 trustfreeconnection(sock
, 0);
256 static int handletrustauth(trustsocket
*sock
, char *server_name
, char *mac
) {
258 char *password
= NULL
;
259 unsigned char digest
[16];
260 char noncehexbuf
[NONCELEN
* 2 + 1];
261 char hexbuf
[sizeof(digest
) * 2 + 1];
262 trustsocket
*ts
, **pnext
;
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.");
285 for(pnext
=&tslist
;*pnext
;pnext
=&((*pnext
)->next
)) {
287 if(ts
->authed
&& strcmp(ts
->authuser
, server_name
) == 0) {
288 trustkillconnection(ts
, "New connection with same server name.");
290 trustfreeconnection(ts
, 0);
296 strncpy(sock
->authuser
, server_name
, SERVERLEN
);
298 controlwall(NO_OPER
, NL_TRUSTS
, "Successful authentication for policy socket with servername '%s'.", server_name
);
299 return trustdowrite(sock
, "AUTHOK");
303 static int handletrustline(trustsocket
*sock
, char *line
) {
304 char *command
, *p
, *lastpos
;
305 char *tokens
[MAXTOKENS
];
306 int tokensfound
= -1;
308 for(command
=lastpos
=p
=line
;*p
;p
++) {
311 if(tokensfound
== MAXTOKENS
)
312 return trustkillconnection(sock
, "too many tokens");
314 if(tokensfound
>= 0) {
315 tokens
[tokensfound
++] = lastpos
;
323 if(tokensfound
== MAXTOKENS
)
324 return trustkillconnection(sock
, "too many tokens");
325 tokens
[tokensfound
++] = lastpos
;
328 if(!sock
->authed
&& !strcmp("AUTH", command
)) {
330 return trustkillconnection(sock
, "incorrect arg count for command.");
332 return handletrustauth(sock
, tokens
[0], tokens
[1]);
333 } else if(sock
->authed
&& !strcmp("CHECK", command
)) {
335 return trustkillconnection(sock
, "incorrect arg count for command.");
337 policycheck_auth(sock
, tokens
[0], tokens
[1], tokens
[2]);
339 } else if(!strcmp("VERSION", command
)) {
340 /* Ignore this command for now. */
343 Error("trusts_policy", ERR_WARNING
, "Bad command: %s", command
);
348 static trustsocket
*findtrustsocketbyfd(int fd
) {
349 for(trustsocket
*ts
=tslist
;ts
;ts
=ts
->next
)
356 static int handletrustclient(trustsocket
*sock
) {
357 int r
, remaining
= TRUSTBUFSIZE
- sock
->size
, i
;
361 trustkillconnection(sock
, "Buffer overflow.");
365 r
= read(sock
->fd
, sock
->buf
+ sock
->size
, remaining
);
372 for(c
=sock
->buf
,i
=0;i
<sock
->size
;i
++,c
++) {
376 if(!handletrustline(sock
, lastpos
))
379 lastpos
= c
+ 1; /* is this ok? */
381 sock
->size
-=lastpos
- sock
->buf
;
382 memmove(sock
->buf
, lastpos
, sock
->size
);
387 static void processtrustclient(int fd
, short events
) {
388 trustsocket
*sock
= findtrustsocketbyfd(fd
);
393 if (events
& (POLLPRI
| POLLERR
| POLLHUP
| POLLNVAL
)) {
394 trustfreeconnection(sock
, 1);
399 if(!handletrustclient(sock
))
400 trustfreeconnection(sock
, 1);
403 static void trustdotimeout(void *arg
) {
404 time_t t
= time(NULL
);
405 trustsocket
**pnext
, *sock
;
407 for(pnext
=&tslist
;*pnext
;pnext
=&((*pnext
)->next
)) {
409 if(!sock
->authed
&& t
>= sock
->timeout
) {
410 trustkillconnection(sock
, "Auth timeout.");
412 trustfreeconnection(sock
, 0);
417 static void processtrustlistener(int fd
, short events
) {
418 if(events
& POLLIN
) {
420 char buf
[NONCELEN
* 2 + 1];
422 int newfd
= accept(fd
, NULL
, NULL
), flags
;
426 flags
= fcntl(newfd
, F_GETFL
, 0);
428 Error("trusts_policy", ERR_WARNING
, "Unable to set socket non-blocking.");
433 if(fcntl(fd
, F_SETFL
, flags
|O_NONBLOCK
) < 0) {
434 Error("trusts_policy", ERR_WARNING
, "Unable to set socket non-blocking.");
439 registerhandler(newfd
, POLLIN
|POLLERR
|POLLHUP
, processtrustclient
);
441 sock
= nsmalloc(POOL_TRUSTS
, sizeof(trustsocket
));
443 deregisterhandler(newfd
, 1);
451 if(fread((char *)sock
->nonce
, 1, NONCELEN
, urandom
) != NONCELEN
) {
452 Error("trusts_policy", ERR_WARNING
, "Error getting random bytes.");
453 deregisterhandler(newfd
, 1);
455 nsfree(POOL_TRUSTS
, sock
);
459 sock
->connected
= time(NULL
);
460 sock
->timeout
= time(NULL
) + 30;
463 sock
->unthrottled
= 0;
464 if(!trustdowrite(sock
, "AUTH %s", hmac_printhex(sock
->nonce
, buf
, NONCELEN
))) {
465 Error("trusts_policy", ERR_WARNING
, "Error writing auth to fd %d.", newfd
);
466 deregisterhandler(newfd
, 1);
468 nsfree(POOL_TRUSTS
, sock
);
475 static int createlistenersock(int port
) {
476 struct sockaddr_in s
;
480 memset(&s
, 0, sizeof(struct sockaddr_in
));
481 s
.sin_family
= AF_INET
;
482 s
.sin_addr
.s_addr
= INADDR_ANY
;
483 s
.sin_port
= htons(port
);
485 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
487 Error("trusts_policy", ERR_WARNING
, "Unable to get socket for trustfd.");
492 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof(optval
));
494 if(bind(fd
, (struct sockaddr
*)&s
, sizeof(struct sockaddr_in
)) < 0) {
495 Error("trusts_policy", ERR_WARNING
, "Unable to bind trustfd.");
500 if(listen(fd
, 5) < 0) {
501 Error("trusts_policy", ERR_WARNING
, "Unable to listen on trustfd.");
506 registerhandler(fd
, POLLIN
, processtrustlistener
);
511 static void policycheck_irc(int hooknum
, void *arg
) {
514 long moving
= (long)args
[1];
516 int verdict
, unthrottle
;
521 verdict
= checkconnection(np
->ident
, &np
->ipaddress
, hooknum
, 0, message
, sizeof(message
), &unthrottle
);
523 if(!enforcepolicy_irc
)
524 verdict
= POLICY_SUCCESS
;
527 case POLICY_FAILURE_NODECOUNT
:
528 glinebynick(np
, POLICY_GLINE_DURATION
, message
, GLINE_IGNORE_TRUST
, "trusts_policy");
530 case POLICY_FAILURE_IDENTD
:
531 glinebyip("~*", &np
->ipaddress
, 128, POLICY_GLINE_DURATION
, message
, GLINE_ALWAYS_USER
|GLINE_IGNORE_TRUST
, "trusts_policy");
533 case POLICY_FAILURE_IDENTCOUNT
:
534 glinebynick(np
, POLICY_GLINE_DURATION
, message
, GLINE_ALWAYS_USER
|GLINE_IGNORE_TRUST
, "trusts_policy");
540 static int trusts_cmdtrustpolicyirc(void *source
, int cargc
, char **cargv
) {
541 nick
*sender
= source
;
544 controlreply(sender
, "Use of glines for trust policy enforcement is currently %s.", enforcepolicy_irc
?"enabled":"disabled");
548 enforcepolicy_irc
= atoi(cargv
[0]);
549 controlwall(NO_OPER
, NL_TRUSTS
, "%s %s use of glines for trust policy enforcement.", controlid(sender
), enforcepolicy_irc
?"enabled":"disabled");
550 controlreply(sender
, "Use of glines for trust policy enforcement is now %s.", enforcepolicy_irc
?"enabled":"disabled");
555 static int trusts_cmdtrustpolicyauth(void *source
, int cargc
, char **cargv
) {
556 nick
*sender
= source
;
559 controlreply(sender
, "Trust policy enforcement with IAuth is currently %s.", enforcepolicy_auth
?"enabled":"disabled");
563 enforcepolicy_auth
= atoi(cargv
[0]);
564 controlwall(NO_OPER
, NL_TRUSTS
, "%s %s trust policy enforcement with IAuth.", controlid(sender
), enforcepolicy_auth
?"enabled":"disabled");
565 controlreply(sender
, "Trust policy enforcement with IAuth is now %s.", enforcepolicy_auth
?"enabled":"disabled");
571 static int trusts_cmdtrustsockets(void *source
, int cargc
, char **cargv
) {
572 nick
*sender
= source
;
578 controlreply(sender
, "Server Connected for Accepted Rejected Unthrottled");
580 for(sock
=tslist
;sock
;sock
=sock
->next
)
581 controlreply(sender
, "%-35s %-20s %-15d %-15d %-15d", sock
->authed
?sock
->authuser
:"<unauthenticated connection>", longtoduration(now
- sock
->connected
, 0), sock
->accepted
, sock
->rejected
, sock
->unthrottled
);
583 controlreply(sender
, "-- End of list.");
587 void loadtrustaccounts(void) {
590 memset(trustaccounts
, 0, sizeof(trustaccounts
));
592 accts
= getconfigitems("trusts_policy", "server");
594 Error("trusts_policy", ERR_INFO
, "No servers added.");
596 sstring
**servers
= (sstring
**)(accts
->content
);
598 for(i
=0;i
<accts
->cursi
;i
++) {
603 Error("trusts_policy", ERR_INFO
, "Too many servers specified.");
607 strncpy(server
, servers
[i
]->content
, sizeof(server
));
609 pos
= strchr(server
, ',');
612 Error("trusts_policy", ERR_INFO
, "Server line is missing password: %s", server
);
618 trustaccounts
[i
].used
= 1;
619 strncpy(trustaccounts
[i
].server
, server
, SERVERLEN
);
620 strncpy(trustaccounts
[i
].password
, pos
+1, TRUSTPASSLEN
);
625 static void trustaccounts_rehash(int hooknum
, void *arg
) {
633 countext
= registertgext("count");
637 m
= getconfigitem("trusts_policy", "enforcepolicy_irc");
639 enforcepolicy_irc
= atoi(m
->content
);
641 m
= getconfigitem("trusts_policy", "enforcepolicy_auth");
643 enforcepolicy_auth
= atoi(m
->content
);
645 m
= getconfigitem("trusts_policy", "trustport");
647 trustport
= atoi(m
->content
);
649 trustport
= DEFAULT_TRUSTPORT
;
652 listenerfd
= createlistenersock(trustport
);
656 registerhook(HOOK_TRUSTS_NEWNICK
, policycheck_irc
);
657 registerhook(HOOK_TRUSTS_LOSTNICK
, &policycheck_irc
);
658 registerhook(HOOK_CORE_REHASH
, trustaccounts_rehash
);
660 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.");
661 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.");
662 registercontrolhelpcmd("trustsockets", NO_DEVELOPER
, 0, trusts_cmdtrustsockets
, "Usage: trustsockets\nLists all currently active TRUST sockets.");
664 schedulerecurring(time(NULL
)+1, 0, 5, trustdotimeout
, NULL
);
666 urandom
= fopen("/dev/urandom", "rb");
668 Error("trusts_policy", ERR_ERROR
, "Couldn't open /dev/urandom.");
672 trustsocket
*sock
, *next
;
677 releasetgext(countext
);
679 deregisterhook(HOOK_TRUSTS_NEWNICK
, policycheck_irc
);
680 deregisterhook(HOOK_TRUSTS_LOSTNICK
, policycheck_irc
);
681 deregisterhook(HOOK_CORE_REHASH
, trustaccounts_rehash
);
683 deregistercontrolcmd("trustpolicyirc", trusts_cmdtrustpolicyirc
);
684 deregistercontrolcmd("trustpolicyauth", trusts_cmdtrustpolicyauth
);
685 deregistercontrolcmd("trustsockets", trusts_cmdtrustsockets
);
687 deleteallschedules(trustdotimeout
);
692 if (listenerfd
!= -1)
693 deregisterhandler(listenerfd
, 1);
695 for(sock
=tslist
;sock
;) {
698 trustkillconnection(sock
, "Unloading module.");
699 trustfreeconnection(sock
, 0);