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