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