Author: Bleep <tomh@inxpress.net>
[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  * $Id$
20  *
21  */
22 #include "IPcheck.h"
23 #include "client.h"
24 #include "ircd.h"
25 #include "numnicks.h"       /* NumNick, NumServ (GODMODE) */
26 #include "ircd_alloc.h"
27 #include "s_bsd.h"          /* SetIPChecked */
28 #include "s_debug.h"        /* Debug */
29 #include "s_user.h"         /* TARGET_DELAY */
30 #include "send.h"
31
32 #include <assert.h>
33 #include <stdio.h>          /* NULL ... bleah */
34 #include <string.h>         /* memset */
35
36
37 struct IPTargetEntry {
38   int           count;
39   unsigned char targets[MAXTARGETS];
40 };
41
42 struct IPRegistryEntry {
43   struct IPRegistryEntry*  next;
44   struct IPTargetEntry*    target;
45   unsigned int             addr;
46   unsigned short           last_connect;
47   unsigned char            connected;
48   unsigned char            attempts;
49 };
50
51 /*
52  * Hash table for IPv4 address registry
53  *
54  * Hash table size must be a power of 2
55  * Use 64K hash table to conserve memory
56  */
57 #define IP_REGISTRY_TABLE_SIZE 0x10000
58 #define MASK_16                0xffff
59
60 #define NOW ((unsigned short)(CurrentTime & MASK_16))
61 #define CONNECTED_SINCE(x) (NOW - (x))
62
63 #define IPCHECK_CLONE_LIMIT 2
64 #define IPCHECK_CLONE_PERIOD 20
65 #define IPCHECK_CLONE_DELAY 600
66
67
68 static struct IPRegistryEntry* hashTable[IP_REGISTRY_TABLE_SIZE];
69 static struct IPRegistryEntry* freeList = 0;
70
71 static unsigned int ip_registry_hash(unsigned int ip)
72 {
73   return ((ip >> 16) ^ ip) & (IP_REGISTRY_TABLE_SIZE - 1);
74 }
75
76 static struct IPRegistryEntry* ip_registry_find(unsigned int ip)
77 {
78   struct IPRegistryEntry* entry = hashTable[ip_registry_hash(ip)];
79   for ( ; entry; entry = entry->next) {
80     if (entry->addr == ip)
81       break;
82   }
83   return entry;
84 }
85
86 static void ip_registry_add(struct IPRegistryEntry* entry)
87 {
88   unsigned int bucket = ip_registry_hash(entry->addr);
89   entry->next = hashTable[bucket];
90   hashTable[bucket] = entry;
91 }
92   
93 static void ip_registry_remove(struct IPRegistryEntry* entry)
94 {
95   unsigned int bucket = ip_registry_hash(entry->addr);
96   if (hashTable[bucket] == entry)
97     hashTable[bucket] = entry->next;
98   else {
99     struct IPRegistryEntry* prev = hashTable[bucket];
100     for ( ; prev; prev = prev->next) {
101       if (prev->next == entry) {
102         prev->next = entry->next;
103         break;
104       }
105     }
106   }
107 }
108  
109 static struct IPRegistryEntry* ip_registry_new_entry()
110 {
111   struct IPRegistryEntry* entry = freeList;
112   if (entry)
113     freeList = entry->next;
114   else
115     entry = (struct IPRegistryEntry*) MyMalloc(sizeof(struct IPRegistryEntry));
116
117   assert(0 != entry);
118   memset(entry, 0, sizeof(struct IPRegistryEntry));
119   entry->last_connect = NOW;     /* Seconds since last connect attempt */
120   entry->connected    = 1;       /* connected clients for this IP */
121   entry->attempts     = 1;       /* Number attempts for this IP */
122   return entry;
123 }
124
125 static void ip_registry_delete_entry(struct IPRegistryEntry* entry)
126 {
127   if (entry->target)
128     MyFree(entry->target);
129   entry->next = freeList;
130   freeList = entry;
131 }
132
133 static unsigned int ip_registry_update_free_targets(struct IPRegistryEntry* entry)
134 {
135   unsigned int free_targets = STARTTARGETS;
136
137   if (entry->target) {
138     free_targets = entry->target->count + (CONNECTED_SINCE(entry->last_connect) / TARGET_DELAY);
139     if (free_targets > STARTTARGETS)
140       free_targets = STARTTARGETS;
141     entry->target->count = free_targets;
142   }
143   return free_targets;
144 }
145
146 static void ip_registry_expire_entry(struct IPRegistryEntry* entry)
147 {
148   /*
149    * Don't touch this number, it has statistical significance
150    * XXX - blah blah blah
151    */
152   if (CONNECTED_SINCE(entry->last_connect) > 600) {
153     /*
154      * expired
155      */
156     ip_registry_remove(entry);
157     ip_registry_delete_entry(entry);
158   }
159   else if (CONNECTED_SINCE(entry->last_connect) > 120 && 0 != entry->target) {
160     /*
161      * Expire storage of targets
162      */
163     MyFree(entry->target);
164     entry->target = 0;
165   }
166 }
167
168 /*
169  * ip_registry_expire
170  */
171 static void ip_registry_expire()
172 {
173   int i;
174   struct IPRegistryEntry* entry;
175   struct IPRegistryEntry* entry_next;
176
177   for (i = 0; i < IP_REGISTRY_TABLE_SIZE; ++i) {
178     for (entry = hashTable[i]; entry; entry = entry_next) {
179       entry_next = entry->next;
180       if (0 == entry->connected)
181         ip_registry_expire_entry(entry);
182     }
183   }
184 }
185
186 /*
187  * IPcheck_local_connect
188  *
189  * Event:
190  *   A new connection was accept()-ed with IP number `cptr->ip.s_addr'.
191  *
192  * Action:
193  *   Update the IPcheck registry.
194  *   Return:
195  *     1 : You're allowed to connect.
196  *     0 : You're not allowed to connect.
197  *
198  * Throttling:
199  *
200  * A connection should be rejected when a connection from the same IP number was
201  * received IPCHECK_CLONE_LIMIT times before this connect attempt, with
202  * reconnect intervals of IPCHECK_CLONE_PERIOD seconds or less.
203  *
204  * Free target inheritance:
205  *
206  * When the client is accepted, then the number of Free Targets
207  * of the cptr is set to the value stored in the found IPregistry
208  * structure, or left at STARTTARGETS.  This can be done by changing
209  * cptr->nexttarget to be `now - (TARGET_DELAY * (FREE_TARGETS - 1))',
210  * where FREE_TARGETS may range from 0 till STARTTARGETS.
211  */
212 int ip_registry_check_local(unsigned int addr, time_t* next_target_out)
213 {
214   struct IPRegistryEntry* entry = ip_registry_find(addr);
215   unsigned int free_targets = STARTTARGETS;
216  
217   if (0 == entry) {
218     entry       = ip_registry_new_entry();
219     entry->addr = addr;    /* The IP number of registry entry */
220     ip_registry_add(entry);
221     return 1;
222   }
223   /* Note that this also connects server connects.
224    * It is hard and not interesting, to change that.
225    *
226    * Don't allow more then 255 connects from one IP number, ever
227    */
228   if (0 == ++entry->connected)
229     return 0;
230
231   if (CONNECTED_SINCE(entry->last_connect) > IPCHECK_CLONE_PERIOD)
232     entry->attempts = 0;
233
234   free_targets = ip_registry_update_free_targets(entry);
235   entry->last_connect = NOW;
236
237   if (0 == ++entry->attempts)   /* Check for overflow */
238     --entry->attempts;
239
240   if (entry->attempts < IPCHECK_CLONE_LIMIT) {
241     if (next_target_out)
242       *next_target_out = CurrentTime - (TARGET_DELAY * free_targets - 1);
243   }
244   else if ((CurrentTime - me.since) > IPCHECK_CLONE_DELAY) {
245     /* 
246      * Don't refuse connection when we just rebooted the server
247      */
248 #ifdef NOTHROTTLE 
249     return 1;
250 #else
251     /* Thanks BLMet :) */
252     --entry->connected;
253     return 0;
254 #endif        
255   }
256   return 1;
257 }
258
259 /*
260  * IPcheck_remote_connect
261  *
262  * Event:
263  *   A remote client connected to Undernet, with IP number `cptr->ip.s_addr'
264  *   and hostname `hostname'.
265  *
266  * Action:
267  *   Update the IPcheck registry.
268  *   Return 0 on failure, 1 on success.
269  */
270 int ip_registry_check_remote(struct Client* cptr, int is_burst)
271 {
272   struct IPRegistryEntry* entry = ip_registry_find(cptr->ip.s_addr);
273
274   /*
275    * Mark that we did add/update an IPregistry entry
276    */
277   SetIPChecked(cptr);
278   if (0 == entry) {
279     entry = ip_registry_new_entry();
280     entry->addr = cptr->ip.s_addr;
281     if (is_burst)
282       entry->attempts = 0;
283     ip_registry_add(entry);
284   }
285   else {
286     if (0 == ++entry->connected) {
287       /* 
288        * Don't allow more then 255 connects from one IP number, ever
289        */
290       return 0;
291     }
292     if (CONNECTED_SINCE(entry->last_connect) > IPCHECK_CLONE_PERIOD)
293       entry->attempts = 0;
294     if (!is_burst) {
295       if (0 == ++entry->attempts) {
296         /*
297          * Check for overflow
298          */
299         --entry->attempts;
300       }
301       ip_registry_update_free_targets(entry);
302       entry->last_connect = NOW;
303     }
304   }
305   return 1;
306 }
307
308 /*
309  * IPcheck_connect_fail
310  *
311  * Event:
312  *   This local client failed to connect due to legal reasons.
313  *
314  * Action:
315  *   Neutralize the effect of calling IPcheck_local_connect, in such
316  *   a way that the client won't be penalized when trying to reconnect
317  *   again.
318  */
319 void ip_registry_connect_fail(unsigned int addr)
320 {
321   struct IPRegistryEntry* entry = ip_registry_find(addr);
322   if (entry)
323     --entry->attempts;
324 }
325
326 /*
327  * IPcheck_connect_succeeded
328  *
329  * Event:
330  *   A client succeeded to finish the registration.
331  *
332  * Finish IPcheck registration of a successfully, locally connected client.
333  */
334 void ip_registry_connect_succeeded(struct Client *cptr)
335 {
336   const char*             tr    = "";
337   unsigned int free_targets     = STARTTARGETS;
338   struct IPRegistryEntry* entry = ip_registry_find(cptr->ip.s_addr);
339
340   if (!entry) {
341     Debug((DEBUG_ERROR, "Missing registry entry for: %s", cptr->sock_ip));
342     return;
343   }
344   if (entry->target) {
345     memcpy(cptr->targets, entry->target->targets, MAXTARGETS);
346     free_targets = entry->target->count;
347     tr = " tr";
348   }
349   sendto_one(cptr, ":%s NOTICE %s :on %u ca %u(%u) ft %u(%u)%s",
350              me.name, cptr->name, entry->connected, entry->attempts,
351              IPCHECK_CLONE_LIMIT, free_targets, STARTTARGETS, tr);
352 }
353
354 /*
355  * IPcheck_disconnect
356  *
357  * Event:
358  *   A local client disconnected or a remote client left Undernet.
359  *
360  * Action:
361  *   Update the IPcheck registry.
362  *   Remove all expired IPregistry structures from the hash bucket
363  *     that belongs to this clients IP number.
364  */
365 void ip_registry_disconnect(struct Client *cptr)
366 {
367   struct IPRegistryEntry* entry = ip_registry_find(cptr->ip.s_addr);
368   if (0 == entry) {
369     /*
370      * trying to find an entry for a server causes this to happen,
371      * servers should never have FLAGS_IPCHECK set
372      */
373     return;
374   }
375   /*
376    * If this was the last one, set `last_connect' to disconnect time (used for expiration)
377    */
378   if (0 == --entry->connected) {
379     if (CONNECTED_SINCE(entry->last_connect) > IPCHECK_CLONE_LIMIT * IPCHECK_CLONE_PERIOD) {
380       /*
381        * Otherwise we'd penetalize for this old value if the client reconnects within 20 seconds
382        */
383       entry->attempts = 0;
384     }
385     ip_registry_update_free_targets(entry);
386     entry->last_connect = NOW;
387   }
388   if (MyConnect(cptr)) {
389     unsigned int free_targets;
390     /*
391      * Copy the clients targets
392      */
393     if (0 == entry->target) {
394       entry->target = (struct IPTargetEntry*) MyMalloc(sizeof(struct IPTargetEntry));
395       entry->target->count = STARTTARGETS;
396     }
397     assert(0 != entry->target);
398
399     memcpy(entry->target->targets, cptr->targets, MAXTARGETS);
400     /*
401      * This calculation can be pretty unfair towards large multi-user hosts, but
402      * there is "nothing" we can do without also allowing spam bots to send more
403      * messages or by drastically increasing the ammount of memory used in the IPregistry.
404      *
405      * The problem is that when a client disconnects, leaving no free targets, then
406      * the next client from that IP number has to pay for it (getting no free targets).
407      * But ALSO the next client, and the next client, and the next client etc - until
408      * another client disconnects that DOES leave free targets.  The reason for this
409      * is that if there are 10 SPAM bots, and they all disconnect at once, then they
410      * ALL should get no free targets when reconnecting.  We'd need to store an entry
411      * per client (instead of per IP number) to avoid this.
412      */
413     if (cptr->nexttarget < CurrentTime) {
414         /*
415          * Number of free targets
416          */
417       free_targets = (CurrentTime - cptr->nexttarget) / TARGET_DELAY + 1;
418     }
419     else
420       free_targets = 0;
421     /*
422      * Add bonus, this is pretty fuzzy, but it will help in some cases.
423      */
424     if ((CurrentTime - cptr->firsttime) > 600)
425       /*
426        * Was longer then 10 minutes online?
427        */
428       free_targets += (CurrentTime - cptr->firsttime - 600) / TARGET_DELAY;
429     /*
430      * Finally, store smallest value for Judgement Day
431      */
432     if (free_targets < entry->target->count)
433       entry->target->count = free_targets;
434   }
435 }
436
437 /*
438  * IPcheck_nr
439  *
440  * Returns number of clients with the same IP number
441  */
442 int ip_registry_count(unsigned int addr)
443 {
444   struct IPRegistryEntry* entry = ip_registry_find(addr);
445   return (entry) ? entry->connected : 0;
446 }
447
448 /*
449  * IPcheck_local_connect
450  *
451  * Event:
452  *   A new connection was accept()-ed with IP number `cptr->ip.s_addr'.
453  *
454  * Action:
455  *   Update the IPcheck registry.
456  *   Return:
457  *     1 : You're allowed to connect.
458  *     0 : You're not allowed to connect.
459  *
460  * Throttling:
461  *
462  * A connection should be rejected when a connection from the same IP number was
463  * received IPCHECK_CLONE_LIMIT times before this connect attempt, with
464  * reconnect intervals of IPCHECK_CLONE_PERIOD seconds or less.
465  *
466  * Free target inheritance:
467  *
468  * When the client is accepted, then the number of Free Targets
469  * of the cptr is set to the value stored in the found IPregistry
470  * structure, or left at STARTTARGETS.  This can be done by changing
471  * cptr->nexttarget to be `now - (TARGET_DELAY * (FREE_TARGETS - 1))',
472  * where FREE_TARGETS may range from 0 till STARTTARGETS.
473  */
474 int IPcheck_local_connect(struct in_addr a, time_t* next_target_out)
475 {
476   assert(0 != next_target_out);
477   return ip_registry_check_local(a.s_addr, next_target_out);
478 }
479
480 /*
481  * IPcheck_remote_connect
482  *
483  * Event:
484  *   A remote client connected to Undernet, with IP number `cptr->ip.s_addr'
485  *   and hostname `hostname'.
486  *
487  * Action:
488  *   Update the IPcheck registry.
489  *   Return 0 on failure, 1 on success.
490  */
491 int IPcheck_remote_connect(struct Client *cptr, int is_burst)
492 {
493   assert(0 != cptr);
494   return ip_registry_check_remote(cptr, is_burst);
495 }
496
497 /*
498  * IPcheck_connect_fail
499  *
500  * Event:
501  *   This local client failed to connect due to legal reasons.
502  *
503  * Action:
504  *   Neutralize the effect of calling IPcheck_local_connect, in such
505  *   a way that the client won't be penalized when trying to reconnect
506  *   again.
507  */
508 void IPcheck_connect_fail(struct in_addr a)
509 {
510   ip_registry_connect_fail(a.s_addr);
511 }
512
513 /*
514  * IPcheck_connect_succeeded
515  *
516  * Event:
517  *   A client succeeded to finish the registration.
518  *
519  * Finish IPcheck registration of a successfully, locally connected client.
520  */
521 void IPcheck_connect_succeeded(struct Client *cptr)
522 {
523   assert(0 != cptr);
524   ip_registry_connect_succeeded(cptr);
525 }
526
527 /*
528  * IPcheck_disconnect
529  *
530  * Event:
531  *   A local client disconnected or a remote client left Undernet.
532  *
533  * Action:
534  *   Update the IPcheck registry.
535  *   Remove all expired IPregistry structures from the hash bucket
536  *     that belongs to this clients IP number.
537  */
538 void IPcheck_disconnect(struct Client *cptr)
539 {
540   assert(0 != cptr);
541   ip_registry_disconnect(cptr);
542 }
543
544 /*
545  * IPcheck_nr
546  *
547  * Returns number of clients with the same IP number
548  */
549 unsigned short IPcheck_nr(struct Client *cptr)
550 {
551   assert(0 != cptr);
552   return ip_registry_count(cptr->ip.s_addr);
553 }
554
555 void IPcheck_expire()
556 {
557   static time_t next_expire = 0;
558   if (next_expire < CurrentTime) {
559     ip_registry_expire();
560     next_expire = CurrentTime + 60;
561   }
562 }
563
564