IP sets are a framework inside the Linux kernel, which can be administered by the ipset utility. Depending on the type, an IP set 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.
If you want to
- store multiple IP addresses or port numbers and match against the collection by iptables at one swoop;
- dynamically update iptables rules against IP addresses or ports without performance penalty;
- express complex IP address and ports based rulesets with one single iptables rule and benefit from the speed of IP sets
then ipset may be the proper tool for you.
:~$ sudo apt-get install ipset
- Create Rules of IPs
:~$ ipset create test hash:ip
:~$ ipset add test 184.108.40.206
:~$ ipset add test 220.127.116.11
:~$ ipset add test 18.104.22.168
:~$ ipset add test 22.214.171.124
:~$ ipset add test 126.96.36.199
- Create Rules of net
:~$ ipset create test hash:net
:~$ ipset add test 188.8.131.52/4
:~$ ipset add test 192.168.1.0/24
:~$ iptables -I INPUT --match set --match-set test src --jump DROP
if package’s source ip belong to hash table test, then drop it.
We use the
set module of iptables to enable references to ipset.
src matches the source address of a packet, and
dst matches the destination address.
:~$ ipset create test hash:ip comment
:~$ ipset create test hash:ip comment counters
:~$ ipset save -f blacklist
If there are 10,000 IP addresses to be blocked here, we can only do this with iptables
iptables -I INPUT --source 184.108.40.206 --jump DROP
iptables is matched in the order of the rules, so each data packet needs 10,000 times to read and match the source IP. The time complexity is O (1000), which seriously affects the performance of iptables.
Now we use IPSET to match this 10,000 IP addresses.
ipset create test hash:ip
Now we only use one iptables rule. At this time, we only need to read the source IP once and then perform IP matching in the hash table of IP Sets. The time complexity becomes O (1). We can be seen that the performance of iptables is greatly improved at this time.
- IP Sets