iptables Hashlimit Rate Not Working as Expected

connectionsfirewalliptablesrules

I wrote the following firewall rule:

iptables -A INPUT -m hashlimit –hashlimit 1/hour –hashlimit-burst 3 –hashlimit-mode srcip,dstport –hashlimit-name ssh -j ACCEPT

I was expecting the burst to be recharged by 1 after one hour but actually it is recharged by one even sooner than one minute. I am sending messages from the same source IP and same destination port, so I was expecting it to accept 3 connections and then 1 per hour. But it is accepting more (one every 20-30 seconds). If I use –limit 1/hour I can observe the expected behaviour, but I need to use hashlimit because I need to filter per srcip and dstport. What am I doing wrong?
Thank you!

Best Answer

I think you are running into expiring entries. An exempt from the manpage:

  --hashlimit-burst amount
         Maximum initial number of packets to match: this number gets recharged by
         one every time the limit specified above is not reached, up to this number;
         the default  is  5. When  byte-based rate matching is requested, this
         option specifies the amount of bytes that can exceed the given rate.
         This option should be used with caution -- if the entry expires, the burst
         value is reset too.

And the amount of time any hash entry is saved is specified with the option --hashlimit-htable-expire. I do not know what the default value for this entry is, but I guess it is a lot shorter than one hour, which would explain why you can connect faster than the expected amount.

You should consider tuning those values some more, allowing one per minute for example - in this case, your server only has to remember the last minute's IPs, and not the last hour worth of IPs.