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