2 * IRC - Internet Relay Chat, ircd/IPcheck.c
3 * Copyright (C) 1998 Carlo Wood ( Run @ undernet.org )
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)
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.
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.
20 * @brief Code to count users connected from particular IP addresses.
30 #include "numnicks.h" /* NumNick, NumServ (GODMODE) */
31 #include "ircd_alloc.h"
32 #include "ircd_events.h"
33 #include "ircd_features.h"
34 #include "s_debug.h" /* Debug */
35 #include "s_user.h" /* TARGET_DELAY */
41 /** Stores free target information for a particular user. */
42 struct IPTargetEntry {
43 int count; /**< Number of free targets targets. */
44 unsigned char targets[MAXTARGETS]; /**< Array of recent targets. */
47 /** Stores recent information about a particular IP address. */
48 struct IPRegistryEntry {
49 struct IPRegistryEntry* next; /**< Next entry in the hash chain. */
50 struct IPTargetEntry* target; /**< Recent targets, if any. */
51 struct irc_in_addr addr; /**< IP address for this user. */
52 int last_connect; /**< Last connection attempt timestamp. */
53 unsigned short connected; /**< Number of currently connected clients. */
54 unsigned char attempts; /**< Number of recent connection attempts. */
57 /** Size of hash table (must be a power of two). */
58 #define IP_REGISTRY_TABLE_SIZE 0x10000
59 /** Report current time for tracking in IPRegistryEntry::last_connect. */
60 #define NOW ((unsigned short)(CurrentTime & 0xffff))
61 /** Time from \a x until now, in seconds. */
62 #define CONNECTED_SINCE(x) (NOW - (x))
64 /** Macro for easy access to configured IPcheck clone limit. */
65 #define IPCHECK_CLONE_LIMIT feature_int(FEAT_IPCHECK_CLONE_LIMIT)
66 /** Macro for easy access to configured IPcheck clone period. */
67 #define IPCHECK_CLONE_PERIOD feature_int(FEAT_IPCHECK_CLONE_PERIOD)
68 /** Macro for easy access to configured IPcheck clone delay. */
69 #define IPCHECK_CLONE_DELAY feature_int(FEAT_IPCHECK_CLONE_DELAY)
71 /** Hash table for storing IPRegistryEntry entries. */
72 static struct IPRegistryEntry* hashTable[IP_REGISTRY_TABLE_SIZE];
73 /** List of allocated but unused IPRegistryEntry structs. */
74 static struct IPRegistryEntry* freeList;
75 /** Periodic timer to look for too-old registry entries. */
76 static struct Timer expireTimer;
78 /** Calculate hash value for an IP address.
79 * If this looks like an IPv6 address, only consider the first 64 bits
80 * of the address. Otherwise, only consider the final 32 bits.
81 * @param[in] ip Address to hash.
82 * @return Hash value for address.
84 static unsigned int ip_registry_hash(const struct irc_in_addr *ip)
88 if (ip->in6_16[0] || ip->in6_16[1] || ip->in6_16[2] || ip->in6_16[3] || ip->in6_16[4]) {
89 /* Only use the first 64 bits of address, since the last 64 bits
90 * tend to be under user control. */
91 res = ip->in6_16[0] ^ ip->in6_16[1] ^ ip->in6_16[2] ^ ip->in6_16[3];
93 /* Looks like an IPv4 address. */
94 res = ip->in6_16[6] ^ ip->in6_16[7];
96 return res & (IP_REGISTRY_TABLE_SIZE - 1);
99 /** Find an IP registry entry if one exists for the IP address.
100 * If \a ip looks like an IPv6 address, only consider the first 64 bits
101 * of the address. Otherwise, only consider the final 32 bits.
102 * @param[in] ip IP address to search for.
103 * @return Matching registry entry, or NULL if none exists.
105 static struct IPRegistryEntry* ip_registry_find(const struct irc_in_addr *ip)
107 struct IPRegistryEntry* entry = hashTable[ip_registry_hash(ip)];
108 for ( ; entry; entry = entry->next) {
109 int bits = (ip->in6_16[0] || ip->in6_16[1] || ip->in6_16[2] || ip->in6_16[3] || ip->in6_16[4]) ? 64 : 128;
110 if (ipmask_check(ip, &entry->addr, bits))
116 /** Add an IP registry entry to the hash table.
117 * @param[in] entry Registry entry to add.
119 static void ip_registry_add(struct IPRegistryEntry* entry)
121 unsigned int bucket = ip_registry_hash(&entry->addr);
122 entry->next = hashTable[bucket];
123 hashTable[bucket] = entry;
126 /** Remove an IP registry entry from the hash table.
127 * @param[in] entry Registry entry to add.
129 static void ip_registry_remove(struct IPRegistryEntry* entry)
131 unsigned int bucket = ip_registry_hash(&entry->addr);
132 if (hashTable[bucket] == entry)
133 hashTable[bucket] = entry->next;
135 struct IPRegistryEntry* prev = hashTable[bucket];
136 for ( ; prev; prev = prev->next) {
137 if (prev->next == entry) {
138 prev->next = entry->next;
145 /** Allocate a new IP registry entry.
146 * For members that have a sensible default value, that is used.
147 * @return Newly allocated registry entry.
149 static struct IPRegistryEntry* ip_registry_new_entry()
151 struct IPRegistryEntry* entry = freeList;
153 freeList = entry->next;
155 entry = (struct IPRegistryEntry*) MyMalloc(sizeof(struct IPRegistryEntry));
158 memset(entry, 0, sizeof(struct IPRegistryEntry));
159 entry->last_connect = NOW; /* Seconds since last connect attempt */
160 entry->connected = 1; /* connected clients for this IP */
161 entry->attempts = 1; /* Number attempts for this IP */
165 /** Deallocate memory for \a entry.
166 * The entry itself is prepended to #freeList.
167 * @param[in] entry IP registry entry to release.
169 static void ip_registry_delete_entry(struct IPRegistryEntry* entry)
172 MyFree(entry->target);
173 entry->next = freeList;
177 /** Update free target count for \a entry.
178 * @param[in,out] entry IP registry entry to update.
180 static unsigned int ip_registry_update_free_targets(struct IPRegistryEntry* entry)
182 unsigned int free_targets = STARTTARGETS;
185 free_targets = entry->target->count + (CONNECTED_SINCE(entry->last_connect) / TARGET_DELAY);
186 if (free_targets > STARTTARGETS)
187 free_targets = STARTTARGETS;
188 entry->target->count = free_targets;
193 /** Check whether all or part of \a entry needs to be expired.
194 * If the entry is at least 600 seconds stale, free the entire thing.
195 * If it is at least 120 seconds stale, expire its free targets list.
196 * @param[in] entry Registry entry to check for expiration.
198 static void ip_registry_expire_entry(struct IPRegistryEntry* entry)
201 * Don't touch this number, it has statistical significance
202 * XXX - blah blah blah
204 if (CONNECTED_SINCE(entry->last_connect) > 600) {
208 ip_registry_remove(entry);
209 ip_registry_delete_entry(entry);
211 else if (CONNECTED_SINCE(entry->last_connect) > 120 && 0 != entry->target) {
213 * Expire storage of targets
215 MyFree(entry->target);
220 /** Periodic timer callback to check for expired registry entries.
221 * @param[in] ev Timer event (ignored).
223 static void ip_registry_expire(struct Event* ev)
226 struct IPRegistryEntry* entry;
227 struct IPRegistryEntry* entry_next;
229 assert(ET_EXPIRE == ev_type(ev));
230 assert(0 != ev_timer(ev));
232 for (i = 0; i < IP_REGISTRY_TABLE_SIZE; ++i) {
233 for (entry = hashTable[i]; entry; entry = entry_next) {
234 entry_next = entry->next;
235 if (0 == entry->connected)
236 ip_registry_expire_entry(entry);
241 /** Initialize the IPcheck subsystem. */
242 void IPcheck_init(void)
244 timer_add(timer_init(&expireTimer), ip_registry_expire, 0, TT_PERIODIC, 60);
247 /** Check whether a new connection from a local client should be allowed.
248 * A connection is rejected if someone from the "same" address (see
249 * ip_registry_find()) connects IPCHECK_CLONE_LIMIT times, each time
250 * separated by no more than IPCHECK_CLONE_PERIOD seconds.
251 * @param[in] addr Address of client.
252 * @param[out] next_target_out Receives time to grant another free target.
253 * @return Non-zero if the connection is permitted, zero if denied.
255 int ip_registry_check_local(const struct irc_in_addr *addr, time_t* next_target_out)
257 struct IPRegistryEntry* entry = ip_registry_find(addr);
258 unsigned int free_targets = STARTTARGETS;
261 entry = ip_registry_new_entry();
262 memcpy(&entry->addr, addr, sizeof(entry->addr));
263 ip_registry_add(entry);
266 /* Note that this also connects server connects.
267 * It is hard and not interesting, to change that.
269 * Don't allow more then 255 connects from one IP number, ever
271 if (0 == ++entry->connected)
277 if (CONNECTED_SINCE(entry->last_connect) > IPCHECK_CLONE_PERIOD)
280 free_targets = ip_registry_update_free_targets(entry);
281 entry->last_connect = NOW;
283 if (0 == ++entry->attempts) /* Check for overflow */
286 if (entry->attempts < IPCHECK_CLONE_LIMIT) {
288 *next_target_out = CurrentTime - (TARGET_DELAY * free_targets - 1);
290 else if ((CurrentTime - cli_since(&me)) > IPCHECK_CLONE_DELAY) {
292 * Don't refuse connection when we just rebooted the server
297 assert(entry->connected > 0);
305 /** Check whether a connection from a remote client should be allowed.
306 * This is much more relaxed than ip_registry_check_local(): The only
307 * cause for rejection is when the IPRegistryEntry::connected counter
309 * @param[in] cptr Client that has connected.
310 * @param[in] is_burst Non-zero if client was introduced during a burst.
311 * @return Non-zero if the client should be accepted, zero if they must be killed.
313 int ip_registry_check_remote(struct Client* cptr, int is_burst)
315 struct IPRegistryEntry* entry = ip_registry_find(&cli_ip(cptr));
318 * Mark that we did add/update an IPregistry entry
322 entry = ip_registry_new_entry();
323 memcpy(&entry->addr, &cli_ip(cptr), sizeof(entry->addr));
326 ip_registry_add(entry);
329 if (0 == ++entry->connected) {
331 * Don't allow more then 255 connects from one IP number, ever
335 if (CONNECTED_SINCE(entry->last_connect) > IPCHECK_CLONE_PERIOD)
338 if (0 == ++entry->attempts) {
344 ip_registry_update_free_targets(entry);
345 entry->last_connect = NOW;
351 /** Handle a client being rejected during connection through no fault
352 * of their own. This "undoes" the effect of ip_registry_check_local()
353 * so the client's address is not penalized for the failure.
354 * @param[in] addr Address of rejected client.
356 void ip_registry_connect_fail(const struct irc_in_addr *addr)
358 struct IPRegistryEntry* entry = ip_registry_find(addr);
361 if (0 == --entry->attempts)
366 /** Handle a client that has successfully connected.
367 * This copies free target information to \a cptr from his address's
368 * registry entry and sends him a NOTICE describing the parameters for
370 * @param[in,out] cptr Client that has successfully connected.
372 void ip_registry_connect_succeeded(struct Client *cptr)
375 unsigned int free_targets = STARTTARGETS;
376 struct IPRegistryEntry* entry = ip_registry_find(&cli_ip(cptr));
379 Debug((DEBUG_ERROR, "Missing registry entry for: %s", cli_sock_ip(cptr)));
383 memcpy(cli_targets(cptr), entry->target->targets, MAXTARGETS);
384 free_targets = entry->target->count;
387 sendcmdto_one(&me, CMD_NOTICE, cptr, "%C :on %u ca %u(%u) ft %u(%u)%s",
388 cptr, entry->connected, entry->attempts, IPCHECK_CLONE_LIMIT,
389 free_targets, STARTTARGETS, tr);
392 /** Handle a client that decided to disconnect (or was killed after
393 * completing his connection). This updates the free target
394 * information for his IP registry entry.
395 * @param[in] cptr Client that has exited.
397 void ip_registry_disconnect(struct Client *cptr)
399 struct IPRegistryEntry* entry = ip_registry_find(&cli_ip(cptr));
402 * trying to find an entry for a server causes this to happen,
403 * servers should never have FLAG_IPCHECK set
408 * If this was the last one, set `last_connect' to disconnect time (used for expiration)
410 /* assert(entry->connected > 0); */
411 if (0 == --entry->connected) {
412 if (CONNECTED_SINCE(entry->last_connect) > IPCHECK_CLONE_LIMIT * IPCHECK_CLONE_PERIOD) {
414 * Otherwise we'd penetalize for this old value if the client reconnects within 20 seconds
418 ip_registry_update_free_targets(entry);
419 entry->last_connect = NOW;
421 if (MyConnect(cptr)) {
422 unsigned int free_targets;
424 * Copy the clients targets
426 if (0 == entry->target) {
427 entry->target = (struct IPTargetEntry*) MyMalloc(sizeof(struct IPTargetEntry));
428 entry->target->count = STARTTARGETS;
430 assert(0 != entry->target);
432 memcpy(entry->target->targets, cli_targets(cptr), MAXTARGETS);
434 * This calculation can be pretty unfair towards large multi-user hosts, but
435 * there is "nothing" we can do without also allowing spam bots to send more
436 * messages or by drastically increasing the ammount of memory used in the IPregistry.
438 * The problem is that when a client disconnects, leaving no free targets, then
439 * the next client from that IP number has to pay for it (getting no free targets).
440 * But ALSO the next client, and the next client, and the next client etc - until
441 * another client disconnects that DOES leave free targets. The reason for this
442 * is that if there are 10 SPAM bots, and they all disconnect at once, then they
443 * ALL should get no free targets when reconnecting. We'd need to store an entry
444 * per client (instead of per IP number) to avoid this.
446 if (cli_nexttarget(cptr) < CurrentTime) {
448 * Number of free targets
450 free_targets = (CurrentTime - cli_nexttarget(cptr)) / TARGET_DELAY + 1;
455 * Add bonus, this is pretty fuzzy, but it will help in some cases.
457 if ((CurrentTime - cli_firsttime(cptr)) > 600)
459 * Was longer then 10 minutes online?
461 free_targets += (CurrentTime - cli_firsttime(cptr) - 600) / TARGET_DELAY;
463 * Finally, store smallest value for Judgement Day
465 if (free_targets < entry->target->count)
466 entry->target->count = free_targets;
470 /** Find number of clients from a particular IP address.
471 * @param[in] addr Address to look up.
472 * @return Number of clients known to be connected from that address.
474 int ip_registry_count(const struct irc_in_addr *addr)
476 struct IPRegistryEntry* entry = ip_registry_find(addr);
477 return (entry) ? entry->connected : 0;
480 /** Check whether a client is allowed to connect locally.
481 * @param[in] a Address of client.
482 * @param[out] next_target_out Receives time to grant another free target.
483 * @return Non-zero if the connection is permitted, zero if denied.
485 int IPcheck_local_connect(const struct irc_in_addr *a, time_t* next_target_out)
487 assert(0 != next_target_out);
488 return ip_registry_check_local(a, next_target_out);
491 /** Check whether a client is allowed to connect remotely.
492 * @param[in] cptr Client that has connected.
493 * @param[in] is_burst Non-zero if client was introduced during a burst.
494 * @return Non-zero if the client should be accepted, zero if they must be killed.
496 int IPcheck_remote_connect(struct Client *cptr, int is_burst)
499 return ip_registry_check_remote(cptr, is_burst);
502 /** Handle a client being rejected during connection through no fault
503 * of their own. This "undoes" the effect of ip_registry_check_local()
504 * so the client's address is not penalized for the failure.
505 * @param[in] a Address of rejected client.
507 void IPcheck_connect_fail(const struct irc_in_addr *a)
509 ip_registry_connect_fail(a);
512 /** Handle a client that has successfully connected.
513 * This copies free target information to \a cptr from his address's
514 * registry entry and sends him a NOTICE describing the parameters for
516 * @param[in,out] cptr Client that has successfully connected.
518 void IPcheck_connect_succeeded(struct Client *cptr)
521 ip_registry_connect_succeeded(cptr);
524 /** Handle a client that decided to disconnect (or was killed after
525 * completing his connection). This updates the free target
526 * information for his IP registry entry.
527 * @param[in] cptr Client that has exited.
529 void IPcheck_disconnect(struct Client *cptr)
532 ip_registry_disconnect(cptr);
535 /** Find number of clones of a client.
536 * @param[in] cptr Client whose address to look up.
537 * @return Number of clients known to be connected from that address.
539 unsigned short IPcheck_nr(struct Client *cptr)
542 return ip_registry_count(&cli_ip(cptr));