You should have a look into ipset
.
From the official website:
Ipset may be the proper tool for you [...] to store multiple IP addresses or port numbers and match against the collection by iptables.
[...] (Ipset) may store IP addresses, networks, (TCP/UDP) port numbers, MAC addresses, interface names or combinations of them in a way, which ensures lightning speed when matching an entry against a set.
To use it, you need to create an ipset
, add the IPs
and create an iptables
rule to match with the ipset
:
ipset create blacklist hash:ip hashsize 1400000
ipset add blacklist <IP-ADDRESS>
iptables -I INPUT -m set --match-set blacklist src -j DROP
A real life example of usage can be found here. Notice that it uses ipset restore
instead of going through each IP
in a loop because it’s much more faster.
If your list of IPs
has overlaps, you may want to preprocess it to convert to IP ranges
where possible. Here is an example of a tool to do it. It won't get you better performances with ipset
but it will reduce the size of your list.
On a side note, in term of performances, it is very fast and scale without penalty. As the Cloudflare
's blog mention, there are faster low level approaches; but it's much more complex and only adds a few bytes per seconds, which, unless you have the scale and ambition of a cloud provider, are not worth the effort.