Ban an IP when the server received an amount of data from it

What I need :

There are many result for adding a drop rules by an amount of request per laps of time, but I need to drop by received byte count from a particular address over a period of time.

What I investigated :

I looked at iptables : for the first case, I saw a dedicated match. I also saw the quota match but, the data count is tracked globally.
I have no idea on how to mix the two rules to track the received data per IP.

Other things :

I'm aware tracking the byte count per IP can use a lot of amount of memory, that's why I also want to keep the period short.
I can accepts other methods, as long as there's a detailed example for it.


You can use IPSET with timeout and counter options. This will be seem like this:

#create ipset for accounting with default lifetime 300 secs
ipset create IP_QUOTA_SET hash:ip timeout 300 counters

#create separated rule chain
iptables --new-chain PER_IP_QUOTING

#send packets to chain
iptables -t filter -A INPUT \
  -i <in-iface> --dst <ip>  \
  -p tcp --dport <dstport>  \
  -j PER_IP_QUOTING

#if ip doesn't exist in the set, add it
iptables -t filter -A PER_IP_QUOTING    \
  -m set ! --match-set IP_QUOTA_SET src \
  -j SET --add-set IP_QUOTA_SET src --timeout 300

#if packet exists in the set, check bytes
#if byte counter > quota then close connection
#by sending of tcp-reset packet.
iptables -t filter -A PER_IP_QUOTING    \
  -m set --match-set IP_QUOTA_SET src   \
  --bytes-gt 1000 -j REJECT --reject-with tcp-rst

#pass other packets (for debug purpose)
iptables -t filter -A PER_IP_QUOTING \
  -j RETURN

In this case you can check the list and edit it by ipset command. Show current list with counters and timeouts: ipset list IP_QUOTA_SET.

For details read the documentation.