Andrew Mercer
on this page

What it is

ipset stores IP addresses, networks, ports, or MAC addresses in kernel hash tables that iptables can match with one rule. Blocking 5,000 addresses with 5,000 iptables rules means a linear walk for every packet; a set lookup is effectively constant time. (On nftables, use its native sets instead — see nftables.)

Basic usage

sudo ipset create blocklist hash:ip
sudo ipset add blocklist 198.51.100.7
sudo ipset add blocklist 203.0.113.44

sudo iptables -I INPUT -m set --match-set blocklist src -j DROP

Networks use hash:net:

sudo ipset create blocknets hash:net
sudo ipset add blocknets 192.0.2.0/24

Managing sets

sudo ipset list                      # all sets with members
sudo ipset test blocklist 198.51.100.7
sudo ipset del blocklist 198.51.100.7
sudo ipset flush blocklist           # empty, keep the set
sudo ipset destroy blocklist         # delete (fails if an iptables rule still references it)

Timeouts let entries expire by themselves, which is how tools like fail2ban use it:

sudo ipset create temp_ban hash:ip timeout 3600
sudo ipset add temp_ban 198.51.100.7 timeout 600

Persistence

Sets live in memory only:

sudo ipset save > /etc/ipset.conf
sudo ipset restore < /etc/ipset.conf     # must run before the iptables rules that reference the sets

Debian/Ubuntu ship ipset-persistent (with netfilter-persistent) to automate this.