๐Ÿ“™ Ipset

๐Ÿ“™ Ipset#

Ipset

  • Ipset is an administration tool for managing IP sets in the Linux kernel, which are used to store and efficiently match IP addresses, networks, port numbers, MAC addresses, or combinations of these elements.

  • It extends the functionality of iptables by allowing firewall rules to match entire sets of addresses at once, rather than requiring individual rules for each entry, which significantly improves performance and simplifies configuration, especially with large lists of IPs.

  • IP sets are stored in indexed data structures like hashes, enabling fast lookups even when dealing with thousands of entries.

  • The tool is used in conjunction with iptables, where rules can reference a set using the โ€“match-set option, and sets cannot be destroyed while they are referenced by active iptables rules.

Create.

แ… sudo ipset create blocklist nethash
แ… sudo iptables -I INPUT -m set --match-set blocklist src -j REJECT --reject-with icmp-admin-prohibited

Populate.

แ… sudo for range in $(cat blocklist.txt);do ipset add blocklist "$range";done
แ… sudo ipset add blocklist 47.76.0.0/14
แ… sudo ipset list blocklist

Save and restore.

แ… sudo ipset save > ipset_$(date +%F_%T|sed 's/[:-]//g')
แ… sudo ipset restore < /root/ipset_20250306_145529

Make the ipset persistent.

แ… sudo apt install ipset-persistent iptables-persistent netfilter-persistent
แ… sudo dpkg -l | awk '$1=="ii"&&$2~/persistent/'
ii  ipset-persistent                            1.0.20                                  all          boot-time loader for netfilter rules, ipset plugin
ii  iptables-persistent                         1.0.20                                  all          boot-time loader for netfilter rules, iptables plugin
ii  netfilter-persistent                        1.0.20                                  all          boot-time loader for netfilter configuration

Check service.

แ… sudo systemctl is-enabled netfilter-persistent.service
enabled
แ… sudo ls -trl /etc/iptables/
total 8
-rw-r--r-- 1 root root 127 Jun 20 09:22 ipsets
-rw-r--r-- 1 root root 282 Jun 20 09:22 rules.v4
-rw-r--r-- 1 root root   0 Jun 20 09:22 rules.v6

Important

If the iptables rules are updated, donโ€™t forget to save them.

แ… sudo iptables-save > /etc/iptables/rules.v4

Idem for the ipset.

แ… sudo ipset save > /etc/iptables/ipsets