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