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