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