Allow TOPIC from off-channel services. Preserve user's visibility in
[ircu2.10.12-pk.git] / ircd / IPcheck.c
1 /*
2  * IRC - Internet Relay Chat, ircd/IPcheck.c
3  * Copyright (C) 1998 Carlo Wood ( Run @ undernet.org )
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2, or (at your option)
8  * any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19 /** @file
20  * @brief Code to count users connected from particular IP addresses.
21  * @version $Id$
22  */
23 #include "config.h"
24
25 #include "IPcheck.h"
26 #include "client.h"
27 #include "ircd.h"
28 #include "match.h"
29 #include "msg.h"
30 #include "numnicks.h"       /* NumNick, NumServ (GODMODE) */
31 #include "ircd_alloc.h"
32 #include "ircd_events.h"
33 #include "ircd_features.h"
34 #include "ircd_log.h"
35 #include "s_debug.h"        /* Debug */
36 #include "s_user.h"         /* TARGET_DELAY */
37 #include "send.h"
38
39 /* #include <assert.h> -- Now using assert in ircd_log.h */
40 #include <string.h>
41
42 /** Stores free target information for a particular user. */
43 struct IPTargetEntry {
44   unsigned int  count; /**< Number of free targets targets. */
45   unsigned char targets[MAXTARGETS]; /**< Array of recent targets. */
46 };
47
48 /** Stores recent information about a particular IP address. */
49 struct IPRegistryEntry {
50   struct IPRegistryEntry*  next;   /**< Next entry in the hash chain. */
51   struct IPTargetEntry*    target; /**< Recent targets, if any. */
52   struct irc_in_addr       addr;   /**< IP address for this user. */
53   int                      last_connect; /**< Last connection attempt timestamp. */
54   unsigned short           connected; /**< Number of currently connected clients. */
55   unsigned char            attempts; /**< Number of recent connection attempts. */
56 };
57
58 /** Size of hash table (must be a power of two). */
59 #define IP_REGISTRY_TABLE_SIZE 0x10000
60 /** Report current time for tracking in IPRegistryEntry::last_connect. */
61 #define NOW ((unsigned short)(CurrentTime & 0xffff))
62 /** Time from \a x until now, in seconds. */
63 #define CONNECTED_SINCE(x) (NOW - (x))
64
65 /** Macro for easy access to configured IPcheck clone limit. */
66 #define IPCHECK_CLONE_LIMIT feature_int(FEAT_IPCHECK_CLONE_LIMIT)
67 /** Macro for easy access to configured IPcheck clone period. */
68 #define IPCHECK_CLONE_PERIOD feature_int(FEAT_IPCHECK_CLONE_PERIOD)
69 /** Macro for easy access to configured IPcheck clone delay. */
70 #define IPCHECK_CLONE_DELAY feature_int(FEAT_IPCHECK_CLONE_DELAY)
71
72 /** Hash table for storing IPRegistryEntry entries. */
73 static struct IPRegistryEntry* hashTable[IP_REGISTRY_TABLE_SIZE];
74 /** List of allocated but unused IPRegistryEntry structs. */
75 static struct IPRegistryEntry* freeList;
76 /** Periodic timer to look for too-old registry entries. */
77 static struct Timer expireTimer;
78
79 /** Convert IP addresses to canonical form for comparison.  IPv4
80  * addresses are translated into 6to4 form; IPv6 addresses are left
81  * alone.
82  * @param[out] out Receives canonical format for address.
83  * @param[in] in IP address to canonicalize.
84  */
85 static void ip_registry_canonicalize(struct irc_in_addr *out, const struct irc_in_addr *in)
86 {
87     if (irc_in_addr_is_ipv4(in)) {
88         out->in6_16[0] = htons(0x2002);
89         out->in6_16[1] = in->in6_16[6];
90         out->in6_16[2] = in->in6_16[7];
91         out->in6_16[3] = out->in6_16[4] = out->in6_16[5] = 0;
92         out->in6_16[6] = out->in6_16[7] = 0;
93     } else
94         memcpy(out, in, sizeof(*out));
95 }
96
97 /** Calculate hash value for an IP address.
98  * @param[in] ip Address to hash; must be in canonical form.
99  * @return Hash value for address.
100  */
101 static unsigned int ip_registry_hash(const struct irc_in_addr *ip)
102 {
103   unsigned int res;
104   /* Only use the first 64 bits of address, since the last 64 bits
105    * tend to be under user control. */
106   res = ip->in6_16[0] ^ ip->in6_16[1] ^ ip->in6_16[2] ^ ip->in6_16[3];
107   return res & (IP_REGISTRY_TABLE_SIZE - 1);
108 }
109
110 /** Find an IP registry entry if one exists for the IP address.
111  * If \a ip looks like an IPv6 address, only consider the first 64 bits
112  * of the address. Otherwise, only consider the final 32 bits.
113  * @param[in] ip IP address to search for.
114  * @return Matching registry entry, or NULL if none exists.
115  */
116 static struct IPRegistryEntry* ip_registry_find(const struct irc_in_addr *ip)
117 {
118   struct irc_in_addr canon;
119   struct IPRegistryEntry* entry;
120   ip_registry_canonicalize(&canon, ip);
121   entry = hashTable[ip_registry_hash(&canon)];
122   for ( ; entry; entry = entry->next) {
123     int bits = (ip->in6_16[0] == ntohs(0x2002)) ? 48 : 64;
124     if (ipmask_check(ip, &entry->addr, bits))
125       break;
126   }
127   return entry;
128 }
129
130 /** Add an IP registry entry to the hash table.
131  * @param[in] entry Registry entry to add.
132  */
133 static void ip_registry_add(struct IPRegistryEntry* entry)
134 {
135   unsigned int bucket = ip_registry_hash(&entry->addr);
136   entry->next = hashTable[bucket];
137   hashTable[bucket] = entry;
138 }
139
140 /** Remove an IP registry entry from the hash table.
141  * @param[in] entry Registry entry to add.
142  */
143 static void ip_registry_remove(struct IPRegistryEntry* entry)
144 {
145   unsigned int bucket = ip_registry_hash(&entry->addr);
146   if (hashTable[bucket] == entry)
147     hashTable[bucket] = entry->next;
148   else {
149     struct IPRegistryEntry* prev = hashTable[bucket];
150     for ( ; prev; prev = prev->next) {
151       if (prev->next == entry) {
152         prev->next = entry->next;
153         break;
154       }
155     }
156   }
157 }
158
159 /** Allocate a new IP registry entry.
160  * For members that have a sensible default value, that is used.
161  * @return Newly allocated registry entry.
162  */
163 static struct IPRegistryEntry* ip_registry_new_entry()
164 {
165   struct IPRegistryEntry* entry = freeList;
166   if (entry)
167     freeList = entry->next;
168   else
169     entry = (struct IPRegistryEntry*) MyMalloc(sizeof(struct IPRegistryEntry));
170
171   assert(0 != entry);
172   memset(entry, 0, sizeof(struct IPRegistryEntry));
173   entry->last_connect = NOW;     /* Seconds since last connect attempt */
174   entry->connected    = 1;       /* connected clients for this IP */
175   entry->attempts     = 1;       /* Number attempts for this IP */
176   return entry;
177 }
178
179 /** Deallocate memory for \a entry.
180  * The entry itself is prepended to #freeList.
181  * @param[in] entry IP registry entry to release.
182  */
183 static void ip_registry_delete_entry(struct IPRegistryEntry* entry)
184 {
185   if (entry->target)
186     MyFree(entry->target);
187   entry->next = freeList;
188   freeList = entry;
189 }
190
191 /** Update free target count for \a entry.
192  * @param[in,out] entry IP registry entry to update.
193  */
194 static unsigned int ip_registry_update_free_targets(struct IPRegistryEntry* entry)
195 {
196   unsigned int free_targets = STARTTARGETS;
197
198   if (entry->target) {
199     free_targets = entry->target->count + (CONNECTED_SINCE(entry->last_connect) / TARGET_DELAY);
200     if (free_targets > STARTTARGETS)
201       free_targets = STARTTARGETS;
202     entry->target->count = free_targets;
203   }
204   return free_targets;
205 }
206
207 /** Check whether all or part of \a entry needs to be expired.
208  * If the entry is at least 600 seconds stale, free the entire thing.
209  * If it is at least 120 seconds stale, expire its free targets list.
210  * @param[in] entry Registry entry to check for expiration.
211  */
212 static void ip_registry_expire_entry(struct IPRegistryEntry* entry)
213 {
214   /*
215    * Don't touch this number, it has statistical significance
216    * XXX - blah blah blah
217    */
218   if (CONNECTED_SINCE(entry->last_connect) > 600) {
219     /*
220      * expired
221      */
222     ip_registry_remove(entry);
223     ip_registry_delete_entry(entry);
224   }
225   else if (CONNECTED_SINCE(entry->last_connect) > 120 && 0 != entry->target) {
226     /*
227      * Expire storage of targets
228      */
229     MyFree(entry->target);
230     entry->target = 0;
231   }
232 }
233
234 /** Periodic timer callback to check for expired registry entries.
235  * @param[in] ev Timer event (ignored).
236  */
237 static void ip_registry_expire(struct Event* ev)
238 {
239   int i;
240   struct IPRegistryEntry* entry;
241   struct IPRegistryEntry* entry_next;
242
243   assert(ET_EXPIRE == ev_type(ev));
244   assert(0 != ev_timer(ev));
245
246   for (i = 0; i < IP_REGISTRY_TABLE_SIZE; ++i) {
247     for (entry = hashTable[i]; entry; entry = entry_next) {
248       entry_next = entry->next;
249       if (0 == entry->connected)
250         ip_registry_expire_entry(entry);
251     }
252   }
253 }
254
255 /** Initialize the IPcheck subsystem. */
256 void IPcheck_init(void)
257 {
258   timer_add(timer_init(&expireTimer), ip_registry_expire, 0, TT_PERIODIC, 60);
259 }
260
261 /** Check whether a new connection from a local client should be allowed.
262  * A connection is rejected if someone from the "same" address (see
263  * ip_registry_find()) connects IPCHECK_CLONE_LIMIT times, each time
264  * separated by no more than IPCHECK_CLONE_PERIOD seconds.
265  * @param[in] addr Address of client.
266  * @param[out] next_target_out Receives time to grant another free target.
267  * @return Non-zero if the connection is permitted, zero if denied.
268  */
269 int ip_registry_check_local(const struct irc_in_addr *addr, time_t* next_target_out)
270 {
271   struct IPRegistryEntry* entry = ip_registry_find(addr);
272   unsigned int free_targets = STARTTARGETS;
273
274   if (0 == entry) {
275     entry       = ip_registry_new_entry();
276     ip_registry_canonicalize(&entry->addr, addr);
277     ip_registry_add(entry);
278     return 1;
279   }
280   /* Note that this also connects server connects.
281    * It is hard and not interesting, to change that.
282    *
283    * Don't allow more then 255 connects from one IP number, ever
284    */
285   if (0 == ++entry->connected)
286   {
287     entry->connected--;
288     return 0;
289   }
290
291   if (CONNECTED_SINCE(entry->last_connect) > IPCHECK_CLONE_PERIOD)
292     entry->attempts = 0;
293
294   free_targets = ip_registry_update_free_targets(entry);
295   entry->last_connect = NOW;
296
297   if (0 == ++entry->attempts)   /* Check for overflow */
298     --entry->attempts;
299
300   if (entry->attempts < IPCHECK_CLONE_LIMIT) {
301     if (next_target_out)
302       *next_target_out = CurrentTime - (TARGET_DELAY * free_targets - 1);
303   }
304   else if ((CurrentTime - cli_since(&me)) > IPCHECK_CLONE_DELAY) {
305     /* 
306      * Don't refuse connection when we just rebooted the server
307      */
308 #ifdef NOTHROTTLE 
309     return 1;
310 #else
311     assert(entry->connected > 0);
312     --entry->connected;
313     return 0;
314 #endif        
315   }
316   return 1;
317 }
318
319 /** Check whether a connection from a remote client should be allowed.
320  * This is much more relaxed than ip_registry_check_local(): The only
321  * cause for rejection is when the IPRegistryEntry::connected counter
322  * would overflow.
323  * @param[in] cptr Client that has connected.
324  * @param[in] is_burst Non-zero if client was introduced during a burst.
325  * @return Non-zero if the client should be accepted, zero if they must be killed.
326  */
327 int ip_registry_check_remote(struct Client* cptr, int is_burst)
328 {
329   struct IPRegistryEntry* entry = ip_registry_find(&cli_ip(cptr));
330
331   /*
332    * Mark that we did add/update an IPregistry entry
333    */
334   SetIPChecked(cptr);
335   if (0 == entry) {
336     entry = ip_registry_new_entry();
337     ip_registry_canonicalize(&entry->addr, &cli_ip(cptr));
338     if (is_burst)
339       entry->attempts = 0;
340     ip_registry_add(entry);
341   }
342   else {
343     if (0 == ++entry->connected) {
344       /* 
345        * Don't allow more then 255 connects from one IP number, ever
346        */
347       return 0;
348     }
349     if (CONNECTED_SINCE(entry->last_connect) > IPCHECK_CLONE_PERIOD)
350       entry->attempts = 0;
351     if (!is_burst) {
352       if (0 == ++entry->attempts) {
353         /*
354          * Check for overflow
355          */
356         --entry->attempts;
357       }
358       ip_registry_update_free_targets(entry);
359       entry->last_connect = NOW;
360     }
361   }
362   return 1;
363 }
364
365 /** Handle a client being rejected during connection through no fault
366  * of their own.  This "undoes" the effect of ip_registry_check_local()
367  * so the client's address is not penalized for the failure.
368  * @param[in] addr Address of rejected client.
369  */
370 void ip_registry_connect_fail(const struct irc_in_addr *addr)
371 {
372   struct IPRegistryEntry* entry = ip_registry_find(addr);
373   if (entry)
374   {
375     if (0 == --entry->attempts)
376       ++entry->attempts;
377   }
378 }
379
380 /** Handle a client that has successfully connected.
381  * This copies free target information to \a cptr from his address's
382  * registry entry and sends him a NOTICE describing the parameters for
383  * the entry.
384  * @param[in,out] cptr Client that has successfully connected.
385  */
386 void ip_registry_connect_succeeded(struct Client *cptr)
387 {
388   const char*             tr    = "";
389   unsigned int free_targets     = STARTTARGETS;
390   struct IPRegistryEntry* entry = ip_registry_find(&cli_ip(cptr));
391
392   if (!entry) {
393     Debug((DEBUG_ERROR, "Missing registry entry for: %s", cli_sock_ip(cptr)));
394     return;
395   }
396   if (entry->target) {
397     memcpy(cli_targets(cptr), entry->target->targets, MAXTARGETS);
398     free_targets = entry->target->count;
399     tr = " tr";
400   }
401   sendcmdto_one(&me, CMD_NOTICE, cptr, "%C :on %u ca %u(%u) ft %u(%u)%s",
402                 cptr, entry->connected, entry->attempts, IPCHECK_CLONE_LIMIT,
403                 free_targets, STARTTARGETS, tr);
404 }
405
406 /** Handle a client that decided to disconnect (or was killed after
407  * completing his connection).  This updates the free target
408  * information for his IP registry entry.
409  * @param[in] cptr Client that has exited.
410  */
411 void ip_registry_disconnect(struct Client *cptr)
412 {
413   struct IPRegistryEntry* entry = ip_registry_find(&cli_ip(cptr));
414   if (0 == entry) {
415     /*
416      * trying to find an entry for a server causes this to happen,
417      * servers should never have FLAG_IPCHECK set
418      */
419     return;
420   }
421   /*
422    * If this was the last one, set `last_connect' to disconnect time (used for expiration)
423    */
424   /* assert(entry->connected > 0); */
425   if (0 == --entry->connected) {
426     if (CONNECTED_SINCE(entry->last_connect) > IPCHECK_CLONE_LIMIT * IPCHECK_CLONE_PERIOD) {
427       /*
428        * Otherwise we'd penetalize for this old value if the client reconnects within 20 seconds
429        */
430       entry->attempts = 0;
431     }
432     ip_registry_update_free_targets(entry);
433     entry->last_connect = NOW;
434   }
435   if (MyConnect(cptr)) {
436     unsigned int free_targets;
437     /*
438      * Copy the clients targets
439      */
440     if (0 == entry->target) {
441       entry->target = (struct IPTargetEntry*) MyMalloc(sizeof(struct IPTargetEntry));
442       entry->target->count = STARTTARGETS;
443     }
444     assert(0 != entry->target);
445
446     memcpy(entry->target->targets, cli_targets(cptr), MAXTARGETS);
447     /*
448      * This calculation can be pretty unfair towards large multi-user hosts, but
449      * there is "nothing" we can do without also allowing spam bots to send more
450      * messages or by drastically increasing the ammount of memory used in the IPregistry.
451      *
452      * The problem is that when a client disconnects, leaving no free targets, then
453      * the next client from that IP number has to pay for it (getting no free targets).
454      * But ALSO the next client, and the next client, and the next client etc - until
455      * another client disconnects that DOES leave free targets.  The reason for this
456      * is that if there are 10 SPAM bots, and they all disconnect at once, then they
457      * ALL should get no free targets when reconnecting.  We'd need to store an entry
458      * per client (instead of per IP number) to avoid this.
459      */
460     if (cli_nexttarget(cptr) < CurrentTime) {
461         /*
462          * Number of free targets
463          */
464       free_targets = (CurrentTime - cli_nexttarget(cptr)) / TARGET_DELAY + 1;
465     }
466     else
467       free_targets = 0;
468     /*
469      * Add bonus, this is pretty fuzzy, but it will help in some cases.
470      */
471     if ((CurrentTime - cli_firsttime(cptr)) > 600)
472       /*
473        * Was longer then 10 minutes online?
474        */
475       free_targets += (CurrentTime - cli_firsttime(cptr) - 600) / TARGET_DELAY;
476     /*
477      * Finally, store smallest value for Judgement Day
478      */
479     if (free_targets < entry->target->count)
480       entry->target->count = free_targets;
481   }
482 }
483
484 /** Find number of clients from a particular IP address.
485  * @param[in] addr Address to look up.
486  * @return Number of clients known to be connected from that address.
487  */
488 int ip_registry_count(const struct irc_in_addr *addr)
489 {
490   struct IPRegistryEntry* entry = ip_registry_find(addr);
491   return (entry) ? entry->connected : 0;
492 }
493
494 /** Check whether a client is allowed to connect locally.
495  * @param[in] a Address of client.
496  * @param[out] next_target_out Receives time to grant another free target.
497  * @return Non-zero if the connection is permitted, zero if denied.
498  */
499 int IPcheck_local_connect(const struct irc_in_addr *a, time_t* next_target_out)
500 {
501   assert(0 != next_target_out);
502   return ip_registry_check_local(a, next_target_out);
503 }
504
505 /** Check whether a client is allowed to connect remotely.
506  * @param[in] cptr Client that has connected.
507  * @param[in] is_burst Non-zero if client was introduced during a burst.
508  * @return Non-zero if the client should be accepted, zero if they must be killed.
509  */
510 int IPcheck_remote_connect(struct Client *cptr, int is_burst)
511 {
512   assert(0 != cptr);
513   return ip_registry_check_remote(cptr, is_burst);
514 }
515
516 /** Handle a client being rejected during connection through no fault
517  * of their own.  This "undoes" the effect of ip_registry_check_local()
518  * so the client's address is not penalized for the failure.
519  * @param[in] a Address of rejected client.
520  */
521 void IPcheck_connect_fail(const struct irc_in_addr *a)
522 {
523   ip_registry_connect_fail(a);
524 }
525
526 /** Handle a client that has successfully connected.
527  * This copies free target information to \a cptr from his address's
528  * registry entry and sends him a NOTICE describing the parameters for
529  * the entry.
530  * @param[in,out] cptr Client that has successfully connected.
531  */
532 void IPcheck_connect_succeeded(struct Client *cptr)
533 {
534   assert(0 != cptr);
535   ip_registry_connect_succeeded(cptr);
536 }
537
538 /** Handle a client that decided to disconnect (or was killed after
539  * completing his connection).  This updates the free target
540  * information for his IP registry entry.
541  * @param[in] cptr Client that has exited.
542  */
543 void IPcheck_disconnect(struct Client *cptr)
544 {
545   assert(0 != cptr);
546   ip_registry_disconnect(cptr);
547 }
548
549 /** Find number of clones of a client.
550  * @param[in] cptr Client whose address to look up.
551  * @return Number of clients known to be connected from that address.
552  */
553 unsigned short IPcheck_nr(struct Client *cptr)
554 {
555   assert(0 != cptr);
556   return ip_registry_count(&cli_ip(cptr));
557 }